Member-only story
What Are Python Iterators and Iterables
Learn how iterables, iterators, and generators make looping possible
In Python, an iterable is something you can loop over.
For instance, a list is an iterable object:
numbers = [1,2,3,4,5]for number in numbers:
print(number)
Output:
1
2
3
4
5
Lists are not the only objects that can be looped over. You can do it with tuples, dictionaries, strings, files, and so on.
But how is this possible? What makes these objects iterable? Why are iterators and iterables useful in Python?
Iterables and Iterators in Python
To qualify as an iterable, the object has to implement the __iter__()
method. Let’s inspect a list of numbers using the built-in dir()
method to see if it has one:
numbers = [1,2,3,4,5]print(dir(numbers))
Output:

You can see the list has the __iter__()
method. It is thus an iterable.
For a for loop to work, it calls the __iter__()
method of a list. This method returns an iterator. The loop uses this iterator to step through all the values.
An iterator is an object with a state. It remembers where it is during an iteration. Iterators also know how to get the next value. They do this by using the __next__()
method which is a method each iterator needs to have.
Let’s retrieve the iterator of the numbers
list for inspection:
iter_numbers = iter(numbers)
(This is the same as calling numbers.__iter__()
)
And let’s call dir()
on this to see what methods it has:
print(dir(iter_numbers))
Result:
There’s the __next__()
method that characterizes an iterator.
To Recap
- A list is an iterable because it has the…