[Python-ideas] while conditional in list comprehension ??

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Mon Jan 28 17:19:23 CET 2013


> -1
> This isn't adding a feature that the language can't currently perform. It
can, with itertools, with an explicit 'for' loop and probably other methods.
> List comprehensions are a useful shortcut that should be kept as simple as
possible. The semantics of the proposed 'while' aren't immediately
> obvious, which makes it out of place in list comprehensions, IMO.
> 
> Eli

I thought everything that can be done with a list comprehension can also be
done with an explicit 'for' loop! So following your logic, one would have to
remove comprehensions from the language altogether. In terms of semantics I
do not really see what isn't immediately obvious about my proposal.

Since the question of use cases was brought up: I am working as a scientist,
and one of the uses I thought of when proposing this was that it could be
used in combination with any kind of iterator that can yield an infinite
number of elements, but you only want the first few elements up to a certain
value (note: this is related to, but not the same as saying I want a certain
number of elements from the iterator).

Let´s take the often used example of the Fibonacci iterator and assume you
have an instance 'fibo' of its iterable class implementation, then:

[n for n in fibo while n <10000]

would return a list with all Fibonacci numbers that are smaller than 10000
(without having to know in advance how many such numbers there are).
Likewise, with prime numbers and a 'prime' iterator:

[n for n in prime while n<10000]

and many other scientifically useful numeric sequences.
I would appreciate such a feature, and, even though everything can be solved
with itertools, I think it´s too much typing and thinking for generating a
list quickly.

Best,
Wolfgang








More information about the Python-ideas mailing list