On Mon, Jan 28, 2013 at 5:33 AM, Wolfgang Maier < wolfgang.maier@biologie.uni-freiburg.de> wrote:
Dear all, I guess this is so obvious that someone must have suggested it before: in list comprehensions you can currently exclude items based on the if conditional, e.g.:
[n for n in range(1,1000) if n % 4 == 0]
Why not extend this filtering by allowing a while statement in addition to if, as in:
[n for n in range(1,1000) while n < 400]
Trivial effect, I agree, in this example since you could achieve the same by using range(1,400), but I hope you get the point. This intuitively understandable extension would provide a big speed-up for sorted lists where processing all the input is unnecessary.
Consider this:
some_names=["Adam", "Andrew", "Arthur", "Bob", "Caroline","Lancelot"] # a sorted list of names [n for n in some_names if n.startswith("A")] # certainly gives a list of all names starting with A, but . [n for n in some_names while n.startswith("A")] # would have saved two comparisons
-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