[Tutor] The Zen of List Comprehension

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Aug 18 11:57:33 EDT 2003


On Sun, 17 Aug 2003, Clay Shirky wrote:

> Saying you are going to filter a list before actually filtering it is
> likewise needless verbiage. Instead of saying filter(), just filter
> directly: [ x for x in nums if x > 3 ].


Hi Clay,

Yes, that's very true.  filter() pays off if the test is either already
built-in, or is some boolean function that we've already written.  But for
arbitrary expressions that we might use just once, it is a little more
work to use filter(), and in those cases, we'd prefer using the list
comprehension.


> Add the limitation of operations on single anonymous variables (so
> perlish), and the resultant profusion of lambdas (again, don't say "Now
> I'm going to put a function in-line", just put the function in-line:
> [x*x for x in nums]), and list comprehensions look to me like a huge
> improvement.

Just to clarify: list comprehensions are syntactic improvements: they
don't give us any new capabilities, but they do make those existing
capabilities easier to use.  In academic terms, they are a kind of
"syntactic sugar", since almost everything we can do with list
comprehensions is possible with a direct combination of map() and
filter().

List comprehensions are pretty sweet, though... *grin* I'm glad to hear
that you got them.



It sounds like you're getting more interested about functional
programming.  For a more comprehensive taste of it, you may find David
Mertz's other articles useful.  For example:

http://www-106.ibm.com/developerworks/linux/library/l-cpyiter.html?ca=dgr-lnxw06Itertools

shows off a set of functions from the new 'itertools' library package. His
article shows things that are possible with these functional tools that
don't really have equivalents with list comprehensions.



I personally got exposed to functional programming in one of my college
courses.  If you're interested, the textbook for that course is here:

    http://mitpress.mit.edu/sicp/full-text/book/book.html

It doesn't use Python --- it uses a language called Scheme --- but, in my
opinion, it's one of the nicest CS textbooks I've ever read.  A bit mind
warping, through.  *grin*



Good luck to you!





More information about the Tutor mailing list