Generators, generator expressions, and loops

Steve Keller keller at no.invalid
Fri Nov 16 09:52:14 EST 2018


I have looked at generators, generator expressions, and iterators and
I try to get more familiar with these.

1. How would I loop over all (with no upper bound) integers or all
powers of two, for example?

In C it would be

   for (int i = 0; ; i++) { ... }  or  for (int i = 1; ; i *= 2) { ... }

In Python, I could define a generator

    def powers():
        i = 1
	while True:
	    yield(i)
	    i *= 2

    for i in powers():
        ...

More elegant are generator expressions but I cannot think of a way
without giving an upper limit:

    for i in (2 ** i for i in range(1000000)):
        ...

which looks ugly.  Also, the double for-loop (and also the two loops
in the above exmaple, for + while in the generator) look unnatural,
somehow, i.e. loop over all elements which are created by a loop.

Is there a more beautyful way?

Steve



More information about the Python-list mailing list