Suggestion for impriving list comprehensions

Guido van Rossum guido at
Thu Jul 26 23:33:20 CEST 2001

paul at (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?
And fuzzy: does this include or exclude the first x >= 50?

How about a library of functions for iterator algebra?  E.g.

  def first(n, sq):
      it = iter(sq)
      for i in range(n): yield

  def lessthan(n, sq):
      for x in sq:
          if x >= n: break
          yield x

--Guido van Rossum (home page:

More information about the Python-list mailing list