GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Python Tutorial
  • Data Types
  • Interview Questions
  • Examples
  • Quizzes
  • DSA Python
  • Data Science
  • NumPy
  • Pandas
  • Practice
  • Django
  • Flask
  • Introduction1 min read
  • Input & Output2 min read

This view

  • Original page
  • New address

GeezerVison is showing www.geeksforgeeks.org — Iterators in Python - GeeksforGeeks

geeksforgeeks
search icon
  • Courses
  • Tutorials
  • Interview Prep
  • Python Tutorial
  • Data Types
  • Interview Questions
  • Examples
  • Quizzes
  • DSA Python
  • Data Science
  • NumPy
  • Pandas
  • Practice
  • Django
  • Flask

Iterators in Python

Last Updated : 5 Jun, 2026

An iterator in Python is an object used to traverse through all the elements of a collection (like lists, tuples or dictionaries) one element at a time. It follows the iterator protocol, which involves two key methods:

  • __iter__(): Returns the iterator object itself.
  • __next__(): Returns the next value from the sequence. Raises StopIteration when the sequence ends.

Need For Iterators

Here are some key benefits:

  • Lazy Evaluation: Processes items only when needed, saving memory.
  • Generator Integration: Pairs well with generators and functional tools.
  • Stateful Traversal: Keeps track of where it left off.
  • Uniform Looping: Same for loop works for lists, strings and more.
  • Composable Logic: Easily build complex pipelines using tools like itertools.

Built-in Iterator

Python provides built-in iterators for iterable objects such as strings, lists, tuples, and dictionaries. These iterators allow elements to be accessed one at a time using the next() function.

Example: Let’s start with a simple example using a string. We will convert it into an iterator and fetch characters one by one:

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

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

Output
G
F
G

Explanation:

  • s is an iterable (string).
  • iter(s) creates an iterator.
  • next(it) retrieves characters one by one.

Creating a Custom Iterator

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

Steps to follow:

  • 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 __init__(self, limit):
        self.limit = limit
        self.n = 2

    def __iter__(self):
        return self

    def __next__(self):
        if self.n > self.limit:
            raise StopIteration

        x = self.n
        self.n += 2
        return x


# Create an iterator for even numbers up to 10
even = EvenNumbers(10)

for num in even:
    print(num)

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

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.

Iterator vs Iterable

Although the terms iterator and iterable sound similar, they are not the same. An iterable is any object that can return an iterator, while an iterator is the actual object that performs iteration one element at a time.

Example: Let’s take a list (iterable) and create an iterator from it

Python
# Iterable: list
numbers = [1, 2, 3]

# Iterator: created using iter()
it = iter(numbers)
print(next(it)) 
print(next(it))  
print(next(it))  

Output
1
2
3

Explanation:

  • numbers is an iterable because it can return an iterator.
  • iter(numbers) creates an iterator object it.
  • next(it) function fetches elements one by one until no more items are left.

To make the difference even clearer, let’s summarize it in a simple table:

FeatureIterableIterator
DefinitionAny object that can return an iteratorObject with a state for iteration
Key MethodImplements __iter__()Implements both __iter__() and __next__()
ExamplesList, Tuple, String, Dictionary, SetObjects returned by iter()

Can use next() directly?

No

Yes

Comment

Explore

    Python Fundamentals
    • Introduction1 min read
    • Input & Output2 min read
    • Variables4 min read
    • Operators4 min read
    • Keywords2 min read
    • Data Types4 min read
    • Conditional Statements3 min read
    • Loops3 min read
    • Functions4 min read
    Python Data Structures
    • String4 min read
    • List3 min read
    • Tuples3 min read
    • Dictionary3 min read
    • Set2 min read
    • Arrays5 min read
    Advanced Python
    • OOP Concepts3 min read
    • Exception Handling5 min read
    • File Handling4 min read
    • Python Database2 min read
    • MongoDB3 min read
    • MySQL7 min read
    • Packages4 min read
    • Modules3 min read
    • DSA Libraries5 min read
    • Python GUI2 min read
    Data Science with Python
    • Numpy3 min read
    • Pandas4 min read
    • Matplotlib3 min read
    • Seaborn3 min read
    • StatsModel2 min read
    • Model Building6 min read
    • TensorFlow2 min read
    • PyTorch5 min read
    Web Development with Python
    • Flask3 min read
    • Django5 min read
    • Django ORM4 min read
    • Jinja2 Templating5 min read
    • Django Templates5 min read
    • REST API3 min read
    • Build API with DRF4 min read
    Python Practice
    • Quiz1 min read
    • Practice Problems2 min read
    • Interview Q & A15+ min read
    Courses
    • Placement 360 Course2 min read
    • Data Science 360 Course2 min read
    • AI Engg Course2 min read
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.