iterables vs. iterators made easy
I'll bet you constantly battle with confusion around iterables and iterators. Nearly every single student I have trained does. The similarity of the naming doesn't help, and most of the examples you see don't really illustrate the concepts clearly. Let's see if we can explain them here. But in a way that the understanding will last.
Let's start with iterables. Iterables are variables that appear on the right side of a for loop. So in this case
for name in names:
the iterable is? Yes, names!
Think of it this way to grasp an initial understanding. An iterable does not in and of itself do anything special. It has the ability to be iterated over, hence it is iterable. Examples are strings, lists, tuples, and even files. And more too. They all have the ability to be iterated over.
In the real world, a duck can fly. We could say the duck is "flyable" (has the ability to fly). But that doesnt mean that the duck is flying now, or will ever want to fly. It may be content spending its life swiming and walking. It just doesn't need to be flyable now, although it can if it wants.
And that's true for iterables true. They can be used as an iterator, but maybe they dont need to be. So you can just use them on the right side of for loops, as iterables, and that's it.
So now, what is an iterator and why do we need one?
Well, first, like the duck must have the ability to fly before it takes to the air, so only iterables have the ability to be iterators.
We could say that the duck is lazy by not wanting to use all that effort to fly. And itertors are lazy too, but in a really useful way. This is because an iterator just returns one value as a time, and only when told to (by using __next__()
).
Let's now look at some code, starting with an iterable:
an_iterable = ['a', 'b', 'c']
for letter in an_iterable:
print(letter)
a
b
c
Try typing these examples and see.
Now let's look at an iterable:
an_iterator = iter(an_iterable)
an_iterator.__next__()
'a'
an_iterator.__next__()
'b'
See how lazy the iterator is? It has to be told to do everything! But that can be a very good thing (but that is beyond the scope of this article).
Hopefully now, having read this, you have achieved two things:
- You know the differences between iterable and iterator clearly, and they are committed to memory.
- You can use that knowledge to read lots of other articles that explain how to use these important concepts.
Let me know if this makes sense, and if you have any questions! And does it help?