7.14 Iterators
What really happens when Python iterates over a list?
for i in [2, 3, 5]:
print(i)
2
3
5
Python keeps track of your position in the list and returns the “next” item every time you ask for it. When you reach the end of the list, the loop terminates. It behaves something like this:
the_list = [2, 3, 5]
the_index = 0
while True:
if the_index < len(the_list):
print(the_list[the_index])
the_index += 1
else:
break
2
3
5
This iteration looks like normal progression through the list from the beginning to the end. What “iteration” means is up to you: you can define it to do anything you wish.
the_list = [2, 3, 5]
the_index = len(the_list) - 1
while True:
if the_index >= 0:
print(the_list[the_index])
the_index -= 1
else:
break
5
3
2
In this case, the iteration framework we have set up selects...