On Mon, Jan 28, 2013 at 11:19 AM, Wolfgang Maier <wolfgang.maier@biologie.uni-freiburg.de> wrote:
-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.
Sarcasm will not help your argument. The difference (as I would expect you to know) between the performance of a list comprehension and an explict `for` loop is significant and the comprehension is already a feature of the language. Removing it would be nonsensical.
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.
This is definitely a problematic use case for a simple list comprehension, but the takewhile solution works exactly as expected and even resembles your solution. It is in the standard library and it's performance seems to be fast enough (to me at least, on a 10 year old laptop). And the key phrase here is "simple list comprehension". Yours is in theory a simple list comprehension but is rather a slightly more complex case that can be handled in a barely more complex way. itertools is a part of the standard library that needs more affection, in my opinion and really does its best to accommodate these more complex cases in sensible ways. I am still -1 on this. Cheers, Ian