What Are Iterables and Iterators in Python?
In Python some objects can be looped over, broadly these objects can be divided into two groups: iterator and iterables. An iterable is any object that can be looped over, such as lists, tuples, dictionaries, and strings whereas iterator is an object that enables a programmer to traverse through all the elements of a collection, one element at a time in a forward direction only. Example of an iterator generator.
Understanding Iterables:
An iterable is anything you can iterate over. In Python, objects like lists, tuples, sets, and dictionaries fall into this category. When you use a for
loop, you are implicitly using an iterable. We can move back and forth in iterables only. All the iterables have only the dunder iter method with them.
Example:
Converting an iterable(list) into iterator
myIterator = iter(myList)
Delving into Iterators
An iterator in Python implements two methods, __iter__()
and __next__()
.
The __iter__()
method returns the iterator object itself,
and the __next__()
method returns the next value from the iterator.
Example:
In the example above you can observe that we move only forward in case of iterator.
Creating Custom Iterators:
You can create user defined iterator objects by defining the __iter__()
and __next__()
methods in a class.
Example:
Practical Applications of Iterators and Iterables
Iterators and iterables are extensively used in Python for data processing, parsing logs, handling files, and managing data streams.
Conclusion
Iterator and Iterable are one of the fundamental topics of Python. At high level these two topics helps to understand the working principles of sequential datatypes. Similarly, at deeper level it helps us to unfold the working mechanism of generator and what exactly makes lists and dictionaries iterable.
Therefore, having a bit a deepth knowledge Iterator and Iterable helps users to write efficent codes in Python.