Categories: Python

Python Iterators Examples

Iterators are objects that can be used to iterate all the items in iterable objects such as Lists, Tuples, Dictionaries, and Sets. It means iterators have the capability to traverse through the iterable objects. A few Examples of iterators are enumerate, map, filter, zip, and reversed. Iterators are basically implemented for loops, comprehensions, and generators.

Python Iterator

Let’s create an iterator and print the next item as shown in the above diagram:

# Create a list
sample = [1, 2, 3, 4, 5]

# Create an iterator
sample_iter = iter(sample)

# Print the next item
print(next(sample_iter))
print(next(sample_iter))
print(next(sample_iter))
print(next(sample_iter))
print(next(sample_iter))
Output:

1
2
3
4
5

Create Your own Iterator

In Python, iterators can be created using an iterator object. In order to implement an iterator should have two methods __iter__() and __next__().

  • __iter__(): returns the iterator object itself.
  • __next__(): returns the next value in the sequence.

in order to avoid the iteration going on forever, raise the StopIteration Exception.

# Define class
class sample_iterator:
    def __init__(self, n):
        self.i = 0
        self.n = n
        
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.i < self.n:
            i = self.i
            self.i += 1
            return self.i
        else:
            raise StopIteration

# Create Object
iter_obj =  sample_iterator(9)

print(next(iter_obj))
print(next(iter_obj))
print(next(iter_obj))
print(next(iter_obj))

Output: 
1
2
3
4

Let’s convert the iterator object into a list iterable:

iter_obj =  sample_iterator(9)

print(list(iter_obj))

Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Let’s use the iterator object in For loop:

iter_obj =  sample_iterator(9)

for i in iter_obj:
    print(i, end = " ")

iter_obj =  sample_iterator(9)

while True:
    try:
        x = iter_obj.__next__()
        print(x, end = " ")
    except StopIteration:
        break
Output:
1 2 3 4 5 6 7 8 9 

Avinash Navlani

Recent Posts

MapReduce Algorithm

In this tutorial, we will focus on MapReduce Algorithm, its working, example, Word Count Problem,…

1 month ago

Linear Programming using Pyomo

Learn how to use Pyomo Packare to solve linear programming problems. In recent years, with…

8 months ago

Networking and Professional Development for Machine Learning Careers in the USA

In today's rapidly evolving technological landscape, machine learning has emerged as a transformative discipline, revolutionizing…

10 months ago

Predicting Employee Churn in Python

Analyze employee churn, Why employees are leaving the company, and How to predict, who will…

1 year ago

Airflow Operators

Airflow operators are core components of any workflow defined in airflow. The operator represents a…

1 year ago

MLOps Tutorial

Machine Learning Operations (MLOps) is a multi-disciplinary field that combines machine learning and software development…

1 year ago