Suggestion for impriving list comprehensions

Thomas Bellman bellman at
Fri Jul 27 00:37:20 CEST 2001

Guido van Rossum <guido at> wrote:

> paul at (Paul Svensson) writes:

>> [x for x in fib() while x < 50]

> Neat, but maybe not general enough.  How do you request the first N?

How about one of these:

    l = []
    for i,v in zip(range(N), fib()):


    l = []; g = fib()
    for i in range(N):

or my personal favourite

    map(lambda x,g=fib():, range(N))

Not *every* list needs to be generated using list comprehension,
you know. :-)  (My personal preferens is that every list should
be generated using map(), filter() or reduce(). :-)

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

Exclude.  Definitely exclude.

> 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

Could be usable, but please not in the builtin namespace.  I'm
already starting to feel that the __builtin__ module is a bit
crowded.  Or, well, perhaps not *crowded*, but rather that it is
somewhat a mish-mash of functions that no-one had the energy to
find the proper module for.

Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"Adde parvum parvo magnus acervus erit"       ! bellman @
          (From The Mythical Man-Month)       ! Make Love -- Nicht Wahr!

More information about the Python-list mailing list