Question about list comprehension/standard "for" disparities

Steve Holden steve at holdenweb.com
Wed Mar 31 22:21:17 CEST 2010


Nathan Rice wrote:
> I was just wondering, why the list/generator and standard "for" have
> disparities?
> 
> It would be really nice to be able to do:
> 
> for x in y if foo:
>     ...
> 
> rather than:
> 
> for x in (x for x in y if foo):
>     ...
> 
But it's not much of an issue when you can easily write

for x in y:
    if foo:
        ...

is it? What's the advantage of your preferred format that overrides its
reduced readability?

> Also, from a style standpoint, I prefer to extract the loop logic into a
> function if it's more than a few lines long.  As a result, most of my
> loops are of the form:
> 
> for x in y:
>     bar(x)
> 
> So I frequently end up using map.  As I understand it, there is some
> discussion of removing map() in favor of comprehensions.  Is there any
> reason why the for syntax could not be expanded to accommodate
> statements of the form:
> 
> bar(x) for x in y
> 
> ?
> 
Put parentheses around it and you have a generator expression, which
sounds like it's exactly what you want: a lazy way of producing a
sequence of values:

>>> y = ["this", "that", "and", "the", "other"]
>>> def bar(x):
...     return 2*x
...
>>> ge = (bar(x) for x in y)
>>> ge
<generator object at 0x7ff28f2c>
>>> for x in ge:
...   print x
...
thisthis
thatthat
andand
thethe
otherother
>>>

If you need to use the sequence repeatedly then a list comprehension is
clearly better, since you don't exhaust it by iterating over it.

I doubt map's going to disappear, but neither are comprehensions or
generator expressions.

> This inconsistency really bothered me when I started playing with
> python, and it seems kind of at-odds with the "one right way to do
> things" mentality.
> 
That's the Platonic ideal, but the real world is a dirty place and
Python lives firmly in the real world!

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC                 http://www.holdenweb.com/
UPCOMING EVENTS:        http://holdenweb.eventbrite.com/




More information about the Python-list mailing list