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

Steven D'Aprano steve at pearwood.info
Tue Jan 29 13:09:47 CET 2013


On 29/01/13 00:33, Wolfgang Maier 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]


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)



So there is precedent in at least one other language for this
obvious and useful feature.




-- 
Steven



More information about the Python-ideas mailing list