[Tutor] lambda vs list comp

Steven D'Aprano steve at pearwood.info
Wed Jul 28 00:08:56 CEST 2010

On Wed, 28 Jul 2010 02:44:02 am 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?

Remember that list comprehensions didn't exist until a few years ago, so 
older code will use map() to implement the same functionality.

> >>> l
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Using lowercase L on its own as a name is not recommended, because it 
looks too similar to 1 and hence difficult to read. For example, the 
next line reads to me like "blah blah for x in ONE", I do a 
double-take, read it again, and realise it's actually L.

> >>> ','.join([str(x) for x in l])
> '0,1,2,3,4,5,6,7,8,9,10'

This would be the preferred (or "Pythonic") way to do this for most 
people these days. That, or a generator expression:

','.join(str(x) for x in l)

Using the list comp form is a micro-optimization over the generator 
expression form (it allows join to allocate the memory needed ahead of 
time, since it has a known size).

> >>> ','.join(map(lambda x:str(x), l))
> '0,1,2,3,4,5,6,7,8,9,10'

That is a line of code written by somebody who doesn't quite get it.

There seems to be something about map and lambda that leads so many 
people into making that silly mistake when they wouldn't make it 
elsewhere. You (generic you, not you personally) almost certainly 
wouldn't write:

def mystr(x):
    return str(x)

n = 42
s = mystr(n)

instead of the more obvious s = str(n). But bring map() into it, and 
people make that exact mistake, writing:

map(lambda x: str(x), L)

instead of the simpler and faster:

map(str, L)

Steven D'Aprano

More information about the Tutor mailing list