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
As you say, a for
loop iterates through the elements of a list. The list can contain anything you like, so you can construct a list beforehand that contains each step.
A for
loop can also iterate over a "generator", which is a small piece of code instead of an actual list. In Python, range()
is actually a generator (in Python 2.x though, range()
returned a list while xrange()
was the generator).
For example:
def doubler(x):
while True:
yield x
x *= 2
for i in doubler(1):
print i
The above for
loop will print
1
2
4
8
and so on, until you press Ctrl+C.