Skip to content
scipython.com

Q4.3.1List comprehension and lambda functions

Rewrite the list of lambda functions created in Example E4.11 using a single list comprehension.

Show solution

The list comprehension:

flist = [lambda x, i=i: x**i for i in range(4)]

creates the same list of anonymous functions as that in Example E4.11. Note that we need to pass each i in to the lambda function explicitly or else Python's closure rules will lead to every lambda function being equivalent to x**3 (3 being the final value of i in the loop).