[Python-ideas] Is this PEP-able? for X in ListY while conditionZ:
Steven D'Aprano
steve at pearwood.info
Wed Jun 26 04:18:50 CEST 2013
On 26/06/13 04:12, Stephen J. Turnbull wrote:
> Shane Green writes:
>
> > [x for x in l if x < 10 else break]?
>
> That's currently invalid syntax: break is a statement. I think a
> while clause (as suggested by David Mertz) would be a more plausible
> extension of syntax.
>
> I do think extending generator/comprehension syntax is much more
> plausible than extending for loop syntax (for one thing, "just use
> break" is not an answer here!)
Comprehensions in Clojure have this feature.
http://clojuredocs.org/clojure_core/clojure.core/for
;; :when continues through the collection even if some have the
;; condition evaluate to false, like filter
user=> (for [x (range 3 33 2) :when (prime? x)]
x)
(3 5 7 11 13 17 19 23 29 31)
;; :while stops at the first collection element that evaluates to
;; false, like take-while
user=> (for [x (range 3 33 2) :while (prime? x)]
x)
(3 5 7)
(expr for x in seq while cond) is not expandable into a for loop in quite the same way as (expr for x in seq if cond) is:
result = []
for x in seq:
if cond:
result.append(expr)
vs
result = []
for x in seq:
if cond:
result.append(expr)
else:
break
but I think it is a natural extension to the generator syntax that fills a real need (or is at least frequently requested), is understandable, and has precedent in at least one other language. But Nick Coghlan has ruled it's not going to happen, although I don't understand what he had against it.
--
Steven
More information about the Python-ideas
mailing list