The Wayback Machine - https://web.archive.org/web/20250304100030/https://www.geeksforgeeks.org/iterators-in-python/
Open In App

Iterators in Python

Last Updated : 16 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

An iterator in Python is an object that holds a sequence of values and provide sequential traversal through a collection of items such as lists, tuples and dictionaries. . The Python iterators object is initialized using the iter() method. It uses the next() method for iteration.

  1. __iter__(): __iter__() method initializes and returns the iterator object itself.
  2. __next__(): the __next__() method retrieves the next available item, throwing a StopIteration exception when no more items are available.

Difference between Iterator and Iterable

Iterables are objects that can return an iterator. These include built-in data structures like lists, dictionaries, and sets. Essentially, an iterable is anything you can loop over using a for loop. An iterable implements the __iter__() method, which is expected to return an iterator object.

Iterators are the objects that actually perform the iteration. They implement two methods: __iter__() and __next__(). The __iter__() method returns the iterator object itself, making iterators iterable as well.

Python iter() Example

Python
s = "GFG"
it = iter(s)

print(next(it))
print(next(it))
print(next(it))

Output
G
F
G

Creating an iterator

Creating a custom iterator in Python involves defining a class that implements the __iter__() and __next__() methods according to the Python iterator protocol.

  • Define the Class: Start by defining a class that will act as the iterator.
  • Initialize Attributes: In the __init__() method of the class, initialize any required attributes that will be used throughout the iteration process.
  • Implement __iter__(): This method should return the iterator object itself. This is usually as simple as returning self.
  • Implement __next__(): This method should provide the next item in the sequence each time it’s called.

Below is an example of a custom class called EvenNumbers, which iterates through even numbers starting from 2:

Python
class EvenNumbers:
    def __iter__(self):
        self.n = 2  # Start from the first even number
        return self

    def __next__(self):
        x = self.n
        self.n += 2  # Increment by 2 to get the next even number
        return x

# Create an instance of EvenNumbers
even = EvenNumbers()
it = iter(even)

# Print the first five even numbers
print(next(it))  
print(next(it)) 
print(next(it))  
print(next(it)) 
print(next(it))  

Output
2
4
6
8
10

Explanation:

  • Initialization: The __iter__() method initializes the iterator at 2, the first even number.
  • Iteration: The __next__() method retrieves the current number and then increases it by 2, ensuring the next call returns the subsequent even number.
  • Usage: We create an instance of EvenNumbers, turn it into an iterator and then use the next() function to fetch even numbers one at a time.

StopIteration Exception

The StopIteration exception is integrated with Python’s iterator protocol. It signals that the iterator has no more items to return. Once this exception is raised, further calls to next() on the same iterator will continue raising StopIteration.

Example:

Python
li = [100, 200, 300]
it = iter(li)

# Iterate until StopIteration is raised
while True:
    try:
        print(next(it))
    except StopIteration:
        print("End of iteration")
        break

Output
100
200
300
End of iteration

In this example, the StopIteration exception is manually handled in the while loop, allowing for custom handling when the iterator is exhausted.


Level up your coding with DSA Python in 90 days! Master key algorithms, solve complex problems, and prepare for top tech interviews. Join the Three 90 Challenge—complete 90% of the course in 90 days and earn a 90% refund. Start your Python DSA journey today!


Next Article
Article Tags :
Practice Tags :

Similar Reads

Infinite Iterators in Python
Iterator in Python is any python type that can be used with a ‘for in loop’. Python lists, tuples, dictionaries, and sets are all examples of inbuilt iterators. But it is not necessary that an iterator object has to exhaust, sometimes it can be infinite. Such type of iterators are known as Infinite iterators. Python provides three types of infinite
2 min read
How to Compare Two Iterators in Python
Python iterators are powerful tools for traversing through sequences of elements efficiently. Sometimes, you may need to compare two iterators to determine their equality or to find their differences. In this article, we will explore different approaches to compare two iterators in Python. Compare Two Iterators In PythonBelow are the ways to compar
3 min read
Combinatoric Iterators in Python
An iterator is an object that can be traversed through all its values. Simply put, iterators are data type that can be looped upon. Generators are iterators but as they cannot return values instead they yield results when they are executed, using the 'yield' function. Generators can be recursive just like functions. These recursive generators which
4 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
Python | Convert list to Python array
Sometimes while working in Python we can have a problem in which we need to restrict the data elements to just one type. A list can be heterogeneous, can have data of multiple data types and it is sometimes undesirable. There is a need to convert this to a data structure that restricts the type of data.Convert List to Array PythonBelow are the meth
2 min read
Python | PRAW - Python Reddit API Wrapper
PRAW (Python Reddit API Wrapper) is a Python module that provides a simple access to Reddit’s API. PRAW is easy to use and follows all of Reddit’s API rules.The documentation regarding PRAW is located here.Prerequisites: Basic Python Programming SkillsBasic Reddit Knowledge : Reddit is a network of communities based on people's interests. Each of
3 min read
Python Debugger – Python pdb
Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to the Python standard library. It is actually defined as the class Pdb which internally makes use of bdb(basic debugger functions) and cmd (support for line-oriented command interpreters) modules. The major advantage of pdb is it runs purely in the command line
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Python: Iterating With Python Lambda
In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python. Syntax: lambda variable : expression Where, variable is used in the expressionexpression can be an mathematical expressio
2 min read
What is Python Used For? | 7 Practical Python Applications
Python is an interpreted and object-oriented programming language commonly used for web development, data analysis, artificial intelligence, and more. It features a clean, beginner-friendly, and readable syntax. Due to its ecosystem of libraries, frameworks, and large community support, it has become a top preferred choice for developers in the ind
8 min read