[Baypiggies] lambda for newbies

Tung Wai Yip tungwaiyip at yahoo.com
Fri May 11 18:53:06 CEST 2007


On Fri, 11 May 2007 01:03:44 -0700, Shannon -jj Behrens <jjinux at gmail.com>  
wrote:

> These days, with list comprehensions, you can just write:
>>>> doubled = [double(i) for i in items]

> A more traditional lisp approach is to use the map function:
>>>> doubled = map(double, items)

Whether list comprehension is more readable than functional programming is  
in the eyes of beholder. When I was learning Python, it takes me a long  
time to learn to read list comprehension. First of all it has a relative  
unique syntax not found in other major language. Secondly Python throw a  
lot of keywords into the syntax without distinctive punctuations. In its  
general form, list comprehesion looks like a jumble of characters:

     [256 - p for p in m if p > 0]

Is it readable? Not for me initially. Eventually I have learned to break  
it down into three parts like below. Only then do each fragment make sense  
to me.

     [256 - p  ...  for p in m  ...  if p > 0]

Still it is not alway easy for my eyes to parse. I wish my editor can be  
more smart to do some syntax highlighting for me. I actually find the  
Haskell syntax, the construct that inspired Python, more readable because  
of the punctuations it uses:

     [256 - p | p <- m, p > 0]


Looking at JJ little example above I would say map(double, items) is more  
readable than list comprehesion. Of course this is my subjective  
judgement. And it assume the user already have a method double defined.  
Otherwise they will have to use lambda to define it on the fly and  
readability start to suffer:

     map(lambda x: x * 2, items)

There are some idioms I that I frequently used that is expressed quite  
nicely with map() and filter().

>>> l = ['peter', '', 'paul']
>>> filter(None, l)
['peter', 'paul']

>>> s = 'peter, paul, mary'
>>> map(str.strip, s.split(','))
['peter', 'paul', 'mary']

Again this is probably depends on your background. I guess people with  
more mathematical training will be more receptive to functional  
programming.

Wai Yip


P.S.
The map(str.strip,x) example I have used is semi broken. It fails when  
there is unicode string. Can't wait the day when text string is always  
unicode.


More information about the Baypiggies mailing list