[Tutor] lamda in list comp
Danny Yoo
dyoo at hashcollision.org
Mon Mar 30 03:16:32 CEST 2015
On Sat, Mar 28, 2015 at 6:25 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> Shouldn't this give me a list of squares?
> [lambda x: x**2 for x in range(10)]
>
> Instead I'm getting ten of these (with different addresses)
> <function <listcomp>.<lambda> at 0x01262A50>]
Mark Lawrence's answer shows how to correct this.
Let's look at the problem a little more closely. To do so, one thing
we can do is rewrite to try removing the use of lambdas. Here's a
fairly similar situation to what you had:
######################
def square(x):
return x * x
[square for x in range(10)]
######################
If you saw that last expression, you might notice a mistake: we
haven't called the function on an argument!
We wanted to say:
[square(x) for x in range(10)]
Once we understand this, let's go back to your original expression:
[lambda x: x**2 for x in range(10)]
If we wanted to revise this so that it applied the function, we can do that:
[(lambda x: x**2)(x) for x in range(10)]
If you're a functional programmer, Python's list comprehension syntax
will take a slight re-adjustment. List comprehensions do sort-of the
same sort of thing as a functional map, but since it's built-in
syntax, it does a bit more, in that the "mapper" is an expression that
directly involves the mapped values.
More information about the Tutor
mailing list