Suggestion for impriving list comprehensions

Thomas Bellman bellman at lysator.liu.se
Thu Jul 26 18:37:20 EDT 2001


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

> paul at svensson.org (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.append(v)

or

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

or my personal favourite

    map(lambda x,g=fib(): g.next(), 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 it.next()

>  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 @ lysator.liu.se
          (From The Mythical Man-Month)       ! Make Love -- Nicht Wahr!



More information about the Python-list mailing list