Should have guessed it
I have sort of a love/hate relationship with Python, the programming language. Coming from PHP and Java which both have excellent documentation, while lots can be said about the solutions. With Python 2.6 the documentation really has improved, but its still not really there, while the solutions are so elegant that the only reason you don’t guess how to do stuff is that it feels too simple.
Today I had one of these realizations, while reading Wayne’s snippet of the day.
Python has a really nice list-generation scheme, so you can generate lists of the content you want from another list of object with only one line of code.
Example:
>>> from math import floor >>> a = [1.5, 1.9, 2.5, 3.1, 5.7] >>> b = [floor(i) for i in a] >>> print b [1.0, 1.0, 2.0, 3.0, 5.0] |
Here I generated a list of whole numbers from a list of non-whole numbers.
Now We’ll take this further.
Lets say we want to filter the list, so we’ll only get the numbers that satisfy 1<=x<2.
We could do this using filter() and lambda functions. Which is totally OK. It'll make Python newbies totally confused (which it did with me until recently, when I realized what lambda functions really are (I'll get back to this)), but it'll work nicely.
But wouldn't it be nice if we could use the same list generation scheme for this as well?
Guess what. You can!
>>> a = [1.5, 1.9, 2.5, 3.1, 5.7] >>> b = [i for i in a if 1<=i and i<2] >>> print b [1.5, 1.9] |
Doing the same using filter and a lambda function will look like this
>>> a = [1.5, 1.9, 2.5, 3.1, 5.7] >>> b = filter(lambda x: 1<=x and x<2, a) >>> print b [1.5, 1.9] |
and without using a lambda function:
>>> def myfilter(x): >>> return x: 1<=x and x<2 >>> a = [1.5, 1.9, 2.5, 3.1, 5.7] >>> b = filter(myfilter, a) >>> print b [1.5, 1.9] |
All of these will work equally fine, and none of them is very hard to understand, as long as you keep in mind that lambda functions just are like anonymous functions/classes.
But there is something very facinating with the elegance and simplicity in the syntax of the list generator snippet.



