List Comprehension Syntax

Moosebumps crap at crap.crap
Sat Jul 10 03:46:23 EDT 2004


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