possibly trivial newbie list/array question

Skip Montanaro skip at pobox.com
Thu Aug 23 10:04:14 EDT 2001


    Paul> Can you tell me the actual purpose of list comprehension?  
    Paul>         [f(x) for x in a]

    Paul> just seems like confusing syntactic hair that's otherwise
    Paul> equivalent to, though as we've seen sometimes slower than,

    Paul>         map(lambda x: f(x), a).

    Paul> Am I missing something?  Unless there's more to it than I see
    Paul> (which is quite possible), I don't understand why this feature
    Paul> made it into the language.

List comprehensions can be more complex than the example you showed and they
run in the scope of the function they are enclosed in, so, unlike lambda,
they have access to all the current crop of local variables without
resorting to default arg hacks or requiring nested scopes.  Section 5.14 of
the Python tutorial gives a few more examples.  None of them are terribly
complex, but that is a tutorial, after all. ;-)

I was never much of a Lisper, so I'm not sure how you'd write the following
list comprehensions

    >>> vec1 = [2, 4, 6]
    >>> vec2 = [4, 3, -9]
    >>> [x*y for x in vec1 for y in vec2]
    [8, 6, -18, 16, 12, -36, 24, 18, -54]
    >>> [x*y for x in vec1 for y in vec2 if y > 3]
    [8, 16, 24]
    >>> [x*y for x in vec1 for y in vec2 if y >= 3]
    [8, 6, 16, 12, 24, 18]

using just map and lambda (I'll throw in filter for free ;-).  If you could,
I suspect it would be fairly inscrutable for the average Python programmer.

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list