Suggestion for impriving list comprehensions

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


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?
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 it.next()

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

--Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-list mailing list