comprehensions was Re: Switch statements again

Dave Brueck dave at pythonapocrypha.com
Thu Jan 16 21:12:09 CET 2003


On Thu, 16 Jan 2003, Jack Diederich wrote:

> > FWIW, I found simple list comprehensions to be one of the least taxing
> > Pythonisms to get used to - IMO the syntax maps very obviously to the
> > behavior.
[snip]
> l = [x for x in l if x > 5]
>                   ^^^^^^^^^
>
> The actual action is hidden at the end, we're doing a filter()

Hidden? In what way?

One other thing I like about comprehensions is that, as they become
more complex, their readability (IMO) often degrades more slowly than when
you use an alternate approach, e.g. to me the following is still very
readable even though it does a lot more than the original example:

[v.split() for k,v in d.items() if k > 0]

I'm generally not a big fan of trying to squeeze a lot into a single line
of code, but comprehensions like the above are common exceptions because I
don't find them obscure or confusing.

> Less of a good reason, but map() and filter() exist in other languages
> so they are more broadly recognizable even to newbies.

Which languages (besides Lisp-ish ones) are you thinking of? Are the
languages common enough and are map/filter used commonly enough in those
languages to really constitute a large percentage of newbies? Just curious
about what you mean.

In any case, I'm not opposed to map/filter/etc - I just don't use them
that often - but I've always had a tough time understanding criticisms of
list comprehensions. :)

Have fun,
Dave





More information about the Python-list mailing list