Introduction to Iterators in Python

Introduction to Iterators in Python

2 mins read488 Views Comment
Updated on Jan 2, 2024 14:35 IST

Have you ever wondered how Python handles looping through collections such as lists or dictionaries? This is where iterators come into play. An iterator in Python is an object that contains a countable number of values and can be iterated upon, meaning you can traverse through all the values. Let's understand more!

2022_09_MicrosoftTeams-image-53.jpg

Iterators in Python are implemented using the  __iter__() and __next__() methods. 

  • __iter__(): This method is used to initialize an iterator that returns an iterator object. 
  • __next__(): This method is used to return the next value within an iterable. This method raises a StopIteration signal at the completion of iterations over the iterable. 

Iterators in Python come in pretty handy while dealing with a huge amount of data.  Here rather than storing all the data in the memory, we work with small chunks of data, and once done processing, we further can use an iterator to stream the rest of the data and start processing the same. This reduces the burden on our computer’s memory. 

Abstraction in Python
Abstraction in Python
In this article, we will discuss abstraction in python and how to implement abstraction using abstract classes and methods.

Now that we have a basic understanding of iterators in Python let’s take a look at the following key concepts associated with them. 

  1. Difference between Iterable and Iterator 
  2. Using for loop as Iterator in Python 
  3. Creating Custom Iterators in Python 

Python Sorted() Function
Python Sorted() Function
The sorted() function is designed to return a new sorted list from the items in an iterable. Whether you're dealing with numbers, strings, or custom objects, sorted() can handle it...read more

Difference Between Iterable and Iterator 

In Python, objects like lists, tuples, strings, sets, etc, are known as iterable objects as they act as a container that can be iterated over using iterators. The iter() is used upon the iterable objects to generate iterators. Take a look at the below example for reference. 

Example: 


 
# initialize an iterable
# object(ie, list)
my_list = [1,2,3,4,5]
#initialize an iterator object
# using iter() method
my_iterator = iter(my_list)
# iterate my_list once by
# calling next() method
print(next(my_iterator))
# iterate my_list twice by
# calling next() method
print(next(my_iterator))
# iterate my_list thrice by
# calling next() method
print(next(my_iterator))
Copy code

Output

2

Using the for Loop as Iterator 

We can also make use of the for loop to iterate over an iterable object. Take a look at the below example for reference. 

Variables in Python
Variables in Python
In this article, we will discuss variables in python, how to name them and how to work with the variables.

Example: Using for loop to iterate over an iterable object. 


 
# initialize a string, that
# is an iterable object in python
my_string = "Shiksha"
# iterate over my_string using for loop
for i in my_string:
print(i)
Copy code

Output: 

S
h
i
k
s
h
a

Creating Iterators in Python 

We make use of the __iter__() and the __next__() method to implement Python iterators. Take a look at the below example for reference. 

Keywords in Python
Keywords in Python
Python has set of keywords that are reserved words, that can’t be used for variable name, function name, or any other identifiers. In this article, we will briefly discuss all...read more

Example: A simple Python program to demonstrate the working of iterators using an example type that iterates from 0 to a given value. 


 
class MyIterable:
# Constructor
def __init__(self, max_value):
self.max_value = max_value
# Initialize iterator and
# create the iterator object
def __iter__(self):
self.a = 0
return self
# Method to get to the next element
# of the iterable
def __next__(self):
# Store current value of a
a = self.a
# Stop iteration if
# max_value is reached
if a > self.max_value:
raise StopIteration
# Else increment and return old value
self.a += 1
return a
# Prints numbers from 0 to 5
for i in MyIterable(5):
print(i)
Copy code

Output: 

0
1
2
3
4
5

Conclusion: 

In this article, we have managed to cover the following concepts associated with Python iterators: 

  • What are Python iterators? 
  • Why use Python iterators? 
  • Difference between iterable and iterators. 
  • Built-in Python iterators
  • Creating a custom Python iterator 
About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio