[Tutor] lambda vs list comp

Rich Lovely roadierich at googlemail.com
Tue Jul 27 19:31:12 CEST 2010


On 27 July 2010 17:53, Mac Ryan <quasipedia at gmail.com> wrote:
> On Tue, 2010-07-27 at 09:44 -0700, Jon Crump wrote:
>> Just as a matter of curiosity piqued by having to understand someone
>> else's code. Is the difference here just a matter of style, or is one
>> better somehow than the other?
>>
>> >>> l
>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>
>> >>> ','.join([str(x) for x in l])
>> '0,1,2,3,4,5,6,7,8,9,10'
>>
>> >>> ','.join(map(lambda x:str(x), l))
>> '0,1,2,3,4,5,6,7,8,9,10'
>
> Considering that "readability metters" I would go for none of the two,
> but for:
>
> ','.join(map(str, l))
>
> (Indeed defining a lambda function that simply uses "str" is redundant)
>
> Just my personal take on this, though!
> Mac.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

There's very little difference between the two in the example you're
using, in python 2.x.  It's a different matter if you want to do
something slightly more complex, or of you're using Python 3.

The benefit of list comprehensions is that they can take a number of
iterables and filter clauses:

>>> [x+y for x in range(3) for y in range(3) if x!=y]
[1, 2, 1, 3, 2, 3]

I can't see any easy way of doing something like that using just map,
fliter and so on.

In python 3, map is a different sort of beast.  Instead of returning a
list, it returns an iterable called a "mapping".  It stores the
original list and the function, and only calls the function when you
ask it for the next value.  You can get similar behaviour in python2
using the imap function in the itertools module.  It's extremely
useful if you need to deal with massive lists of millions of elements
- where making the list every time would take too long.

-- 
Rich "Roadie Rich" Lovely

Just because you CAN do something, doesn't necessarily mean you SHOULD.
In fact, more often than not, you probably SHOULDN'T.  Especially if I
suggested it.

10 re-discover BASIC
20 ???
30 PRINT "Profit"
40 GOTO 10


More information about the Tutor mailing list