For loops
suggest changefor loops iterate over a collection of items, such as list or dict, and run a block of code with each element from the collection.
for i in [0, 1, 2, 3, 4]:
print(i)
The above for loop iterates over a list of numbers.
Each iteration sets the value of i to the next element of the list. So first it will be 0, then 1, then 2, and so on. The output will be as follows:
0
1
2
3
4
range returns an iterable sequence of numbers, so it can be used in for loops:
for i in range(5):
print(i)
gives the exact same result as the first for loop. Note that 5 is not printed as the range here is the first five numbers counting from 0.
Iterable objects and iterators
A for loop can iterate over any iterable. An object is iterable if it defines __iter__, or if it defines __getitem__ for successive integer indexes. __iter__ returns an iterator, whose __next__ method produces the next element. In Python 3 that method is __next__, not next.