List Comprehension Syntax

Larry Bates lbates at swamisoft.com
Mon Jul 12 21:03:58 CEST 2004


I don't agree that the second is "less maintainable",
but do find it "wordy" for little reason.  Try:

result=[x.replace('blah','moof') for x in L if x.startswith('blah')]

or if you prefer short lines:

result=[x.replace('blah','moof') \
        for x in L \
        if x.startswith('blah')]

Note: BAD idea to call variable 'list' as it kills the
list function for remainder of Python session (I changed
to L).  For same reason never call variable 'dict', 'str',
etc.  Using startswith also takes care of not having to
get the slice correct (which is easier to maintain should
you change 'blah' to something else, you don't have to
mess with the slice).

Larry Bates
Syscon, Inc.

"Moosebumps" <crap at crap.crap> wrote in message
news:j9NHc.8596$mJ3.4258 at newssvr25.news.prodigy.com...
> Does anyone here find the list comprehension syntax awkward?
>
> I like it because it is an expression rather than a series of statements,
> but it is a little harder to maintain it seems.
>
> e.g. you could do:
>
> result = []
> for element in list:
>     if element[0:4] == 'blah':
>         result.append( element.replace( 'blah', 'moof' ) )
>
> or just:
>
> result = [ element.replace( 'blah', 'moof' ) for element in list if
> element[0:4] == 'blah' ]
>
> The second looks cleaner in some cases, but it is less maintainable.  It
> tends to promote long lines.  It all seems to run together and such.  And
> often you would need to add another condition or modify it, it seems
better
> to use the first way even though it has the ugly extra init (and which
would
> cause more allocs than the list comprehension?  because it wouldn't know
the
> size off the bat?)
>
> I am in favor of short lines like I think Guido said in the style guide.
I
> like each line to be so simple as to not require any thinking reading it,
> e.g.
>
> I prefer:
>
> x = c( d, e )
> y = f( g, h )
> z = b( x, y )
> w = a( z )
>
> to stuff like this:
>
> w = a( b( c( d, e ), f( g, h ) ) )
>
> It is more maintainable, when you need to make a change, just insert a
line,
> rather than having to decode an expression.
>
> Along the same lines, it seems more maintainable to split things up.
>
> You could do:
>
> result = [
>     element.replace( 'blah', 'moof' )
>         for element in list
>             if element[0:4] == 'blah' ]
>
> I guess, but that seems awkward to me.  Looks too much like a for loop and
> an if, and then the value is at the top, which reads funny to me.
> (Strangely putting it on one line doesn't read as funny, but it is less
> readable.)  Maybe I just have to get used to it.  Which do you prefer?
> Comments?
>
> MB
>
>





More information about the Python-list mailing list