It’s Day 10. Let’s talk about the for
loop. But not in the way you think.
The Iterator Protocol and Pythonic Looping
00:00 I remember when I learned this topic, the one we’re going to cover today for the first time, and it was one of those wow moments in the sense that I realized that I’m finally starting to understand Python at a deeper level, and I still find this topic really fascinating.
00:16
Our starting point is one of the most basic things in Python. In fact, when you were first learning Python, I’m sure that one of the very first things you learned about was the for
loop.
00:28
And the for
loop comes in its simplest form. And then yes, you can have some more complex looking for
loops. For example, if you’re looping through the dictionary items, if you’ve covered this, you know it looks a bit different.
00:41
But the question is what happens within a for
loop? And I don’t mean we go through each item of the object and do something with it. That’s the high level that we understand early on what really happens within Python when we’re on the for
loop.
00:58
Incidentally, this applies to other iteration in Python, not just the for
loop, but I’m using the for
loop because it’s one of the most basic forms of iteration.
01:07 And unsurprisingly, there are dunder methods to deal with these. And there are also two terms that until you get comfortable with them, can be confusing: iterable and iterator.
01:20
So a data type is an iterable if you can use it in a for
loop, if you can iterate through it, which means if you can go through it one item at a time.
01:31
Now the for
loop or other iteration processes in Python takes this iterable. For example, a list is an iterable, a string is an iterable, and it converts it to a different data type, something called an iterator.
01:45 And you learn all about the difference between iterable and iterator today. And then the iterator is what fetches one item at a time and gives it over, yields.
01:58
It is the term I’m going to use to Python into the for
loop in this case and this process of having an iterable and then its matching iterator.
02:06 Sometimes the same data type serves as both, which makes things a bit more interesting and puts more flavor to this topic. And once you understand, this is called iterator protocol.
02:18
Looping for
loops, but other iteration as well will make a lot more sense. So hope you enjoy today’s topic.
You must own this product to join the conversation.