Iterators and Iterables

Python
March 22, 2018

Iterables are something that you can iterate on or something out of which you can create an iterator object. Any iterable object can be converted to an iterator with the help of iter() method. Iterable can be finite like list, tuple, string, dictionary, set, etc and also be an infinite flow of data like open files, open socket, etc.

Iterators are stateful (& helper) object that can return data in the form of a single element when they are called with next() method.

Using iter() with a non-iterable object, will raise a TypeError. While using next() on an iterable will also generate a TypeError.

If we can use iter() on an object then, the object is an iterable, and if we can use next() on an object then, the object is an iterator.

Iterable and Iterator, both are  something that we can iterate on, but Iterator is stateful, while Iterable is not. By stateful, I mean that it remembers the state it was left in. Iterators can remember what state they left in, while Iterators cannot.

We can use loops with both Iterables and Iterators. Infact, everytime we use for, it gives a call to the iter() method. Here, l will be first converted to iterator with the help of iter() method and every time the loop is enetered, next() method will be called.

Reference – [1] http://nvie.com/posts/iterators-vs-generators/