What are Iterables and Iterators in Python
Breaking the ‘iterating confusion’ around these terms.
--
While writing an article about Generators, I realized that though iteration, iterable and iterator are so commonly used in programming; there is a certain degree of confusion around them. It’s crucial to understand the underlying concept for a better implementation. This is going to be a short and quick article to help us determine what is an iterable and what is an iterator.
Iteration
- In layman’s language it is ‘repeating steps’.
- Iteration in programming is a repetition of a block of code for a certain number of times.
- This can be achieved by using loops.
Iterable
- Iterable is an object which can be looped over or iterated over.
e.g. List, Tuple, Set, Dictionary, File. - In simpler words, iterable is a container which has data or values and we perform iteration over it to get elements one by one. (Can traverse through these values one by one)
- Iterable has an in-built dunder method __iter__. A simpler way to determine whether an object is iterable is to check if it supports __iter__. How? Using dir( ), it returns the list of attributes and methods supported by an object.
Iterator
- Iterator is an iterable object with a state so it remembers where it is during iteration.
e.g. Generator - Iterator performs the iteration to access the elements of the iterable one by one. As it maintains the internal state of elements, iterator knows how to get the next value.
- Iterators can only move forward using __next__ . It cannot go back or cannot be reset.
- Iterator supports in-built dunder methods __iter__ and __next__.
Let’s try to make sense out of all these. Say, I have 10 chips in my ‘Can of Pringles’. Taking out chips one by one several times can be referred as iteration.