List Comprehension Syntax

Ville Vainio ville at spammers.com
Sat Jul 10 06:39:57 EDT 2004


>>>>> "Moosebumps" == Moosebumps  <crap at crap.crap> writes:

    Moosebumps> Does anyone here find the list comprehension syntax awkward?

...

    Moosebumps> I am in favor of short lines like I think Guido said
    Moosebumps> in the style guide.  I like each line to be so simple
    Moosebumps> as to not require any thinking reading it,

You need to think of the total complexity involved with having several
lines. When you see a list comprehension, you know what to expect -
transformation and/or filtering applied to a list. Therefore, you can
easily read and write out the beast.

LC's also encourage the list transformation/filtering approach to
problems, which I find absolutely splendid. Appending elements to a
list manually is tedious, especially if the problem really is a
stereotypical problem solved by a LC (and interestingly, most problems
are ;-).

    Moosebumps> You could do:

    Moosebumps> result = [
    Moosebumps> element.replace( 'blah', 'moof' )
    Moosebumps> for element in list
    Moosebumps> if element[0:4] == 'blah' ]

    Moosebumps> I guess, but that seems awkward to me.  Looks too much
    Moosebumps> like a for loop and an if, and then the value is at
    Moosebumps> the top, which reads funny to me.  (Strangely putting
    Moosebumps> it on one line doesn't read as funny, but it is less
    Moosebumps> readable.)  Maybe I just have to get used to it.
    Moosebumps> Which do you prefer?

It's just a matter of getting used to it. Admittedly LC's are
sometimes confusing for newbies, but they are an example of such a
feature where the tradeoff between newbie and non-newbie friendliness
has really paid off.

Now that genexps are coming around, you'll be facing even bigger
payoffs. So just keep using them, even if they might not feel as
maintanable at the moment. LC's (and genexps even to a bigger extent)
are pretty much what defines the "pythonic" way of doing things for me
these days.

-- 
Ville Vainio   http://tinyurl.com/2prnb



More information about the Python-list mailing list