List Comprehension Syntax

Moosebumps crap at crap.crap
Sat Jul 10 15:52:36 EDT 2004


> I usually do
> result = [
>     element.replace( 'blah', 'moof' )
>     for element in list
>     if element[0:4] == 'blah'
> ]
> It seems clean and logical enough to me - like e.g. defining big dicts.
>
>

But what if you have multiple for and if's?  Seems like you would want to
indent them then.

I think I might just get used to the multiline syntax since LCs are very
useful... it just seems awkward for some reason.

result = [ x for x in blah if f(x) ]

seems more elegant than:

result = [
    x
        for x in blah
            if f(x) ]

but I like to keep things consistent and have maintainability, so then the
second one wins.  i.e. the second one "scales better" to more complicated
expressions!

MB






More information about the Python-list mailing list