parsing a file [newbie]

Alex Martelli aleaxit at yahoo.com
Thu Jan 18 15:44:40 EST 2001


"Syver Enstad" <syver at NOSPAMcyberwatcher.com> wrote in message
news:947jg4$55r$1 at troll.powertech.no...
>
> "Grant Edwards" <grante at visi.com> wrote
>  I could have used a list comprehension instead of a
> > for loop.
>
> Ouch, I feel really stupid to have to ask this question, but what the ...
is
> a list comprehension, and why is it better to use it than a for statement?

It's not necessarily better -- it may be if the gain in concision translates
into clarity.  The syntax, new to Python 2, is in the simplest case, e.g.:

    return [ <expression> for <var> in <sequence> ]

equivalent to:

    result = []
    for <var> in <sequence>:
        result.append(<expression>)
    return result

A compact yet readable single-line, expression way to express a single
high-level concept, can easily be a gain of clarity.  The conditional form:

    return [ <expression> for <var> in <sequence> if <condition> ]

equivalent to:

    result = []
    for <var> in <sequence>:
        if <condition>:
            result.append(<expression>)
    return result

can be at least as much of a clarity gain.

There is no nesting limit to the for and if clauses of the
list-comprehension
syntax, but deep nesting is often not all that clear no matter how you dice
and slice it, so you might be well-advised to refactor things if you find
more
than a couple of for clauses in a comprehension (nesting if clauses hardly
ever makes much sense, since 'if <a> if <b>' is the same as 'if <a> and
<b>').


Alex






More information about the Python-list mailing list