Iterable vs Iterator in Python
Let’s learn about iterables and iterators.
Published in
6 min readJul 24, 2020
Iterator
In Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__() . — python docs
- An iterator is an object representing a stream of data.
- It returns the data one element at a time.
- A Python iterator must support a method called
__next__()
that takes no arguments and always returns the next element of the stream. - If there are no more elements in the stream,
__next__()
must raise the StopIteration exception. - Iterators don’t have to be finite.It’s perfectly reasonable to write an iterator that produces an infinite stream of data.
Iterable
In Python,Iterable is anything you can loop over with a for loop.
An object is called an iterable if u can get an iterator out of it.
- Calling
iter()
function on an iterable gives us an iterator. - Calling
next()
function on iterator gives us the next element. - If the iterator is exhausted(if it has no more elements), calling next() raises
StopIteration
exception.