List Comprehension Syntax

Mitja nun at example.com
Sat Jul 10 14:24:34 EDT 2004


Moosebumps <crap at crap.crap>
(news:j9NHc.8596$mJ3.4258 at newssvr25.news.prodigy.com) wrote:

> 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?

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.





More information about the Python-list mailing list