Suggestion for impriving list comprehensions

Paul Svensson paul at svensson.org
Thu Jul 26 22:00:54 EDT 2001


Guido van Rossum <guido at python.org> writes:

>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?

No need to cover cases that are clearer expressed
without involving a list comprehensions at all.

fib()[:N], I would assume works.


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

No fuzzier than "while x < 50: ..." -- of course it excludes.

>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

Now, there's something I would call "not general enough".

	/Paul



More information about the Python-list mailing list