Computer >> Computer tutorials >  >> Programming >> Python

How to pass Python function as a function argument?


Python implements the following method where the first parameter is a function −

map(function, iterable, ...) - Apply function to every item of iterable and return a list of the results.

We can also write custom functions where we can pass a function as an argument.

We rewrite given code to pass the function sqr(x) as function argument using map method.

Example

s = [1, 3, 5, 7, 9]
def sqr(x): return x ** 2
print(map(sqr, s))
We can as well use lambda function to get same output
s = [1, 3, 5, 7, 9]
print(map((lambda x: x**2), s))

Output

C:/Users/TutorialsPoint1/~.py
[1, 9, 25, 49, 81]