I want to write a for loop that will iterate over the powers of 2 for each loop.
For example I would want a range like this:
2, 4, 8, 16, ... , 1024
You can use a generator expression so that it generates the numbers as needed and they don't waste memory:
>>> for x in (2**p for p in range(1, 11)):
... print(x)
2
4
8
16
32
64
128
256
512
1024
In Python 2, you can use xrange
instead of range
to keep it as a generator and avoid creating unnecessary lists.
If you want to enter the actual stop point instead of the power to stop at, this is probably the simplest way:
from itertools import count
for x in (2**p for p in count(1)):
if x > 1024:
break
print(x)
You could put it all in one line:
from itertools import count, takewhile
for x in takewhile(lambda x: x <= 1024, (2**p for p in count(1))):
print(x)
but that's becoming silly (and not very readable).