March 10, 2008

Python list comprehensions and lambda

Filed under: dev, python — michaelangela @ 10:00 am

Lambda functions (aka anonymous functions) were long a mystery to me. I think it’s just because I didn’t relate anonymous functions to them. Now they make sense, though I can’t claim to understand some of the more convoluted ones I have seen. (Convoluted to me, though not to the authors I am sure.)

List comprehensions took a while also. I was able to guess the meaning but I wasn’t able to actually write one until recently. It kept throwing syntax errors. After upgrading some components suddenly list comprehensions started to work. I thought I was already at least at python 2.5 previously so I am not sure what happened. But now it works. The other part was finding out the name list comprehensions. That actually took a while. It turns out it’s in the docs but I hadn’t gone through that before. It was a bit of luck with Google that I hit on the term “list comprehensions” at which point it all became clearer.

One good summary though is from the creator of web2py:

new appliance and web site! – web2py Web Framework | Google Groups

Example 1:

z=lambda x,y: x+y

you should read “lambda” and “:” as “a function that takes the variables” and “and returns”. Hence the above example reads:

z = a function that takes the variables x,y and returns x+y

and z(3,4) returns 7. There is really nothing more to it.

Example 2:

q=[process(x) for x in somelist if condition(x)]

is a shorthand notation for
for x in somelist:
if condition(x):

That comparison is quite helpful.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: