Suggestion for impriving list comprehensions

Paul Svensson paul at svensson.org
Thu Jul 26 12:48:20 EDT 2001


Tom_Good1 at excite.com (Tom Good) writes:

>The problem with using "for i in fib():" is that fib() will generate
>an infinite set!  Infinite sets are fun to work with, but somewhat
>problematic to output :-)
>
>The example uses "for i in range(9):" instead, in order to generate
>and show only the first few Fibonacci numbers.
>
>Which reminds me, when working with unbounded generators, you can wrap
>them with another generator to restrict their output, with something
>like this:
>
>#------ begin code
>
>def genWhile(g, condition):
>    """
>    run generator g while 'condition' is true.
>    Condition is a partial expression string such as "< 10"
>    to be evaluated with g.next() as the left side
>    """
>    while 1:
>        next = g.next()
>        if eval("next " + condition):
>            yield next
>        else:
>            raise StopIteration
>
>#------ end code
>
>Then you can say, for example:
>
>>>> g = fib()
>>>> [x for x in genWhile(g, "< 50")]
>
>[1, 1, 2, 3, 5, 8, 13, 21, 34]
>.
>...to get the Fibonacci numbers that are less than 50.

This immegiately suggest an obvious language improvement.
Now that we have generators in the language, unbounded sequences
will be much more common, so other ways to terminate list comprehensions
would be increasingly useful.

With the current Python, [x for x in fib() if x < 50] would be the same
as your example above, it would just take forever to do it, since Python
doesn't understand that continuing past the first false condition,
the condition will continue to be false, and no new elements produced.

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]

	/Paul



More information about the Python-list mailing list