How to pass Python function as a function argument?

PythonServer Side ProgrammingProgramming

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.


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))


[1, 9, 25, 49, 81]
Updated on 13-Feb-2020 06:07:23