Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to pass Python function as a function argument?

In the code

s = [1, 3, 5, 7, 9]
def sqr(x): return x ** 2

How do I pass the python function sqr(x) as a function argument?


1 Answer
Rajendra Dharmkar

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

OUTPUT

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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.