Earlier this week I posted a quiz about how many iterators there are in this code
numbers = [2, 5, 10, 3, 99, 42]
for number in numbers:
for another_number in numbers:
print(number, another_number)
…let's explore with the help of this visual aid
A short series
Here's the code again.
The poll gave four options for possible answers for how many iterators there are in this code:
1
2
7
12
Here's the poll, by the way
First, let's just look at the four lines of code and nothing else
There are no iterators visible in the code.
There's one list named `numbers`. This is an iterable
If you're unsure about the difference between iterable and iterator, read on
twitter.com/s_gruppetta_ct/status/1679178647423402005
There are two other variables named `number` and `another_number`
These variables represent the integers you're looping through, and integers are neither iterable nor iterators
And that's it, except for the `print` function and the keywords `for` and `in`
So, no iterators in sight in the lines of code themselves
But 0 wasn't an option in the poll
So let's see what happens as the code runs…
A `for` loop needs an iterable, such as a list
The loop creates an iterator from the iterable
Let's start with the first loop, the outer one. It creates an iterator from the list and the iterator is ready to go, "waiting" just before the list's first element
The loop then gets the first item from this outer loop iterator, which is 2. The iterator stops here for now, between 2 and 5
But then it finds the second, inner, `for` loop statement. This is a new `for` loop. Even though it uses the same list, `numbers`, the inner loop creates a new iterator from the iterable (the list)
Let's call the two iterators inner and outer iterators.
The outer iterator is stuck between 2 and 5 for now, the first and second items in the list, while the inner iterator goes through all the elements of the list
When the inner iterator uses up all the elements, it's exhausted. Iterators can only be used once. They're like disposable items.
The outer iterator can now move on the the next value. And the outer loop now reaches the inner loop again for the second time
It needs to create an iterator again. The previous inner iterator is no longer useful
Here's a representation of the first three iterations of the outer loop. You can figure out the rest
The "checkpoints" you see on the left make sense in the article I'll link to soon…
And this is Part 6 of a series of article about data structure categories. You may also want to read the first one about iterables
open.techwriters.info/thepythoncodingstack/python-iterable-data-structures
And since you're there, go ahead with 2-5 about sequences, mappings, containers, and collections
Make sure you subscribe to get all new articles directly in your inbox about all sorts of Python topics, as always, written in a more relaxed style than your typical technical article!
open.techwriters.info/thepythoncodingstack