Suggestion for impriving list comprehensions

Mark Day mday at apple.com
Fri Jul 27 03:09:21 CEST 2001


In article <cpofq75qax.fsf at cj20424-a.reston1.va.home.com>, Guido van
Rossum <guido at python.org> wrote:

> paul at svensson.org (Paul Svensson) writes:
> 
> > I would like to suggest that we add a "while condition" clause
> > to list comprehensions, similar to the "if condition" clause,
> > but terminating the list comprehension on the first false condition.
> > The above example could then be written as
> > 
> > [x for x in fib() while x < 50]
> 
> Neat, but maybe not general enough.  How do you request the first N?

[x[0] for x in zip(fib(),xrange(N))]

or

[x for x in fib()][:N]

assuming it's smart enough to stop iterating when the slice has been
produced.  I guess the list comprehension would have to be a form of
iterator/generator, and slices would have to stop iterating when they
get all the elements they need.  Would this work in 2.2a1?

> And fuzzy: does this include or exclude the first x >= 50?

I would have assumed it would exclude the first x >= 50.  But then I
tend to think in C and prefer while(){} over do{}while().

Consider:
>>> [3*i for i in xrange(10) if (i%2)==0]
[0, 6, 12, 18, 24]

When I see that list comprehension, I think of it as something like:

for i in xrange(10):
   if (i%2)==0:
      yield 3*i

or

temp = iterator(xrange(10))
while 1:
   i = temp.next()
   if i%2==0:
      yield 3*i

where the while loop terminates when temp returns an exception.

So, [x for x in fib() while x < 50] would be something like:

while (x=fib.next()) < 50:
   yield x

I'm using C notation to express combined assignment and condition test. 
But that's because that concept is a little more cumbersome to express
in Python (and why it would be great in list comprehensions).  I
suppose the Pythonic way would be something like:

x = fib.next()
while x<50:
   yield x
   x = fib.next()

-Mark



More information about the Python-list mailing list