Iterators In Python
The purpose of this article is to examine Python iterators with examples so that they may suit the needs of students.
Python iterators are objects that contain a countable number of values.
The value of an iterator can be traversed many times, indicating that the object can be iterated upon.
Iterators in Python implement the iterator protocol, which consists of the methods iter() and next() methods.
Iterator vs Iterable
An iterator can be obtained from any of these objects by calling their iter() method.
Provide an iterator from a tuple, and display every value:
Display two values with an iterator based on a tuple:
Strings are also iterable objects, and they can be returned as iterators.
A string is also an iterable object, including a sequence of characters:
Strings iterable object Example: 1
Strings iterable object Example: 2
Create an Iterator
You must implement the __iter__() and __next__() methods in your object in order to create an iterator.
In the Python Classes/Objects chapter, you learned that all classes have a function called __init__() that lets you initialize the object.
Similarly, the iter() method permits you to do operations (initializing, etc.), but you must always provide the iterator object.
Additionally, the next() method permits you to perform operations and must provide the next item.
Implementing an iterator to return numbers that increase by five each time (returning 0,5,10,15,20,25, etc.):
Reverse it now – Implement Python iterators to return numbers decreasing by five (returning 25, 20, 15, 10, 5, 0 etc.):
Iterator creation Example: 2
Looping Through an Iterator
Python iterators can also be invoked with a for loop to iterate through an iterable object.
Perform iterations on tuple values:
Iterator For Loop Example: 1
Perform iterations on the characters of a string:
String Iterator For Loop Example: 1
Each loop in a for loop creates an iterator object and executes its next() method.
In a for loop, or if you used enough next() statements, the example above would never end.
By using the StopIteration statement, we can prevent iteration from continuing forever.
We can add a stopping condition to the next() method to return an error if the iteration is done more than a given number of times.
Don’t continue after 50 iterations:
Stop Iteration Example: 1
Reverse It Now:
Iterators In Python Benefits
Iterators in Python offer several benefits, such as:
- Iterators allow for efficient memory utilization when working with large or infinite sequences of data. Instead of loading all the data into memory at once, iterators generate and provide elements one at a time, only when requested. This is particularly useful when dealing with large datasets that cannot fit entirely in memory.
- Iterators support lazy evaluation, meaning that they generate elements on the fly as they are requested. This can significantly improve performance and reduce computation time by avoiding unnecessary computations or generating elements that may not be needed.
- Iterators simplify the process of looping or iterating over a collection of elements. By providing a consistent and standardized interface, such as the
forloop, iterators abstract away the underlying details of data retrieval or generation, making the code more readable and easier to write.
- Iterators allow you to define custom sequence generation logic. By implementing the
__next__()methods in a class, you can create your own iterable objects that produce elements based on specific rules or conditions. This provides flexibility in generating sequences or iterating over complex data structures.
- Iterators seamlessly integrate with built-in functions like
sum(). These functions work with iterators, allowing for concise and efficient data processing operations. This integration enables a functional programming style and promotes code reusability and composability.