I recently started learning Python, and the concept of for loops is still a little confusing for me. I understand that it generally follows the format for x in y
You can use a generator expression to do this efficiently and with little excess code:
for i in (2**x for x in range(10)): #In Python 2.x, use `xrange()`.
...
Generator expressions work just like defining a manual generator (as in Greg Hewgill's answer), with a syntax similar to a list comprehension. They are evaluated lazily - meaning that they don't generate a list at the start of the operation, which can cause much better performance on large iterables.
So this generator works by waiting until it is asked for a value, then asking range(10)
for a value, doubling that value, and passing it back to the for
loop. It does this repeatedly until the range()
generator yields no more values.