Why cannot I use while
in [the syntax for comprehensions and generator expressions]?
It just isn't defined to work that way. Maybe a future version might support it, if there is a clear proposal (PEP) and enough demand.
How can I have an infinite loop within list comprehension?
with a for
clause that loops over some unbounded generator. itertools
provides a couple of those: count
(produces increasing numbers endlessly) and repeat
(keeps yielding the same value, unless an explicit count is provided). Alternately, you can build it yourself from the built-in iter
:
>>> help(iter)
Help on built-in function iter in module builtins:
iter(...)
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator
Get an iterator from an object. In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.
The first version clearly doesn't help, but for the second, all we need is a callable that returns some value, and a sentinel value that is a different value. E.g. iter(lambda: True, False)
.