[Python-ideas] while conditional in list comprehension ?? (original) (raw)
Eli Bendersky eliben at gmail.com
Mon Jan 28 16:55:57 CET 2013
- Previous message: [Python-ideas] while conditional in list comprehension ??
- Next message: [Python-ideas] while conditional in list comprehension ??
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Mon, Jan 28, 2013 at 5:33 AM, Wolfgang Maier < wolfgang.maier at 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: somenames=["Adam", "Andrew", "Arthur", "Bob", "Caroline","Lancelot"] # a sorted list of names [n for n in somenames if n.startswith("A")] # certainly gives a list of all names starting with A, but . [n for n in somenames 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130128/d00c0a97/attachment.html>
- Previous message: [Python-ideas] while conditional in list comprehension ??
- Next message: [Python-ideas] while conditional in list comprehension ??
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]