[Python-ideas] Builtin infinite generator
Collin Winter
collinw at gmail.com
Wed Mar 21 18:35:22 CET 2007
On 3/21/07, Tobias Ivarsson <thobes at gmail.com> wrote:
> Quite often I find myself wanting to write an infinite for-loop, or rather a
> loop with a counter, that terminates on some inner condition. Recently I
> even wanted to do this together with the generator comprehension syntax, I
> don't remember exactly what I wanted to do, but it was something like:
> zip( some_list_of_unknown_length, ('a' for x in infinit_generator) )
> I admit that my example is silly, but it still serves as an example of what
> I wanted to do.
itertools.count()
(http://docs.python.org/lib/itertools-functions.html) handles just
this. Wrapping it in a genexp can take care of the second example:
> >>> for i in range(...):
> ... print i
> ... if i == 4: break
for i in itertools.count():
....
> >>> for i in range(10,...,10):
> ... print i
> ... if i == 40: break
for i in (i * 10 for i in itertools.count(1)):
....
Collin Winter
More information about the Python-ideas
mailing list