user763191 user763191 - 8 months ago 59
Python Question

Python: Lambda function in List Comprehensions

Why is the output of the following two list comprehensions different, even though f and the lambda function are the same ?

f = lambda x: x*x
[f(x) for x in range(10)]


[lambda x: x*x for x in range(10)]

Mind you, both type(f) and type(lambda x: x*x) return the same type.


The first one create a single lambda function and calls it ten times.

The second one doesn't call the function. It creates 10 different lambda functions. It puts all of those in a list. To make it equivalent to the first you need:

[(lambda x: x*x)(x) for x in range(10)]

Or better yet:

[x*x for x in range(10)]