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

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.

 

Python Iterators



Iterator vs Iterable

Iterable objects include lists, tuples, dictionaries, and sets. With Python iterators, they are iterable containers that can be used to create iterators.

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:

Example: 1 

laptop_tuple = ("Apple", "HP", "Dell", "Lenovo") laptop_it = iter(laptop_tuple) print(next(laptop_it)) print(next(laptop_it)) print(next(laptop_it)) print(next(laptop_it))

Display two values with an iterator based on a tuple:

Example: 2 

laptop_tuple = ("Apple", "HP", "Dell", "Lenovo") laptop_it = iter(laptop_tuple) print(next(laptop_it)) print(next(laptop_it))

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 

company_string = "Apple" company_it = iter(company_string) print(next(company_it)) print(next(company_it)) print(next(company_it)) print(next(company_it)) print(next(company_it))

Strings iterable object Example: 2 

company_string = "Mr " laptop_string = "Examples" company_it = iter(company_string) laptop_it = iter(laptop_string) print(next(company_it)) print(next(company_it)) print(next(company_it)) print(next(laptop_it)) print(next(laptop_it)) print(next(laptop_it)) print(next(laptop_it)) print(next(laptop_it)) print(next(laptop_it)) print(next(laptop_it)) print(next(laptop_it))

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.):

Example: 

class Common_difference: def __iter__(mrx): mrx.val = 0 return mrx def __next__(mrx): ample = mrx.val mrx.val += 5 return ample mrxclass = Common_difference() ampleiter = iter(mrxclass) print(next(ampleiter)) print(next(ampleiter)) print(next(ampleiter)) print(next(ampleiter)) print(next(ampleiter)) print(next(ampleiter))

Reverse it now – Implement Python iterators to return numbers decreasing by five (returning 25, 20, 15, 10, 5, 0 etc.):

Iterator creation Example: 2 

class Common_difference: def __iter__(mrx): mrx.val = 25 return mrx def __next__(mrx): ample = mrx.val mrx.val -= 5 return ample mrxclass = Common_difference() ampleiter = iter(mrxclass) print(next(ampleiter)) print(next(ampleiter)) print(next(ampleiter)) print(next(ampleiter)) print(next(ampleiter)) print(next(ampleiter))

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

laptop_tuple = ("Apple", "HP", "Dell", "Lenovo") for mrx in laptop_tuple: print(mrx)

Perform iterations on the characters of a string:

Example: 

laptop_tuple = ("M", "R", " ", "E", "x", "a", "m", "p", "l", "e", "s")for mrx in laptop_tuple: print(mrx)

String Iterator For Loop Example: 1

laptop_string = "Mr Examples" for mrx in laptop_string: print(mrx)

Each loop in a for loop creates an iterator object and executes its next() method.


Stop Iteration

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 

class Common_difference: def __iter__(mrx): mrx.val = 0 return mrxdef __next__(mrx): if mrx.val <= 50: ample = mrx.val mrx.val += 5 return ample else: raise StopIterationmrxclass = Common_difference() ampleiter = iter(mrxclass)for a in ampleiter: print(a)

Reverse It Now:

Example: 

class Common_difference: def __iter__(mrx): mrx.val = 50 return mrxdef __next__(mrx): if mrx.val >= 0: ample = mrx.val mrx.val -= 5 return ample else: raise StopIteration mrxclass = Common_difference() ampleiter = iter(mrxclass)for a in ampleiter: print(a)

Iterators In Python Benefits

Iterators in Python offer several benefits, such as:

  1. 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.
  2. 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.
  3. Iterators simplify the process of looping or iterating over a collection of elements. By providing a consistent and standardized interface, such as the for loop, iterators abstract away the underlying details of data retrieval or generation, making the code more readable and easier to write.
  4. Iterators allow you to define custom sequence generation logic. By implementing the __iter__() and __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.
  5. Iterators seamlessly integrate with built-in functions like next(), iter(), map(), filter(), and 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.
To appreciate our efforts or suggest improvements for this site, kindly leave your reaction below.
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *