Reputation: 895
According to the syntax specification of comprehension ,[x for x in (1,2,3) if lambda x :x-2]
is valid. However,[x for x in (1,2,3)]
has the same result .What impact does the lambda section have in this list comprehension?
Upvotes: 0
Views: 40
Reputation: 532478
It has no impact. The lambda
expression defines a function
object, and the if
guard in a list comprehension expects a Boolean value. The "truthiness" of a function
object is always True
, so the list comprehension is exactly the same as
[x for x in (1,2,3) if True]
If you actually called the resulting function, such as with
[x for x in (1,2,3) if (lambda y :y-2)(x)]
then you would have an actual filter that effectively checks if a value is not equal to 2. (y - 2
will be non-zero, and thus True
, for any value of y
other than 2.)
Upvotes: 6