0
0
PythonHow-ToBeginner · 3 min read

How to Make Object Iterable in Python: Simple Guide

To make an object iterable in Python, define the __iter__ method that returns an iterator object, which itself implements the __next__ method. This allows the object to be used in loops and other iterable contexts.
📐

Syntax

To make an object iterable, implement the __iter__ method that returns an iterator. The iterator must implement the __next__ method, which returns the next item or raises StopIteration when done.

  • __iter__(self): Returns the iterator object (usually self).
  • __next__(self): Returns the next value or raises StopIteration.
python
class MyIterable:
    def __iter__(self):
        return self  # returns the iterator object

    def __next__(self):
        # return next item or raise StopIteration
        raise StopIteration
💻

Example

This example shows a class that counts from 1 to 3, making it iterable with for loops.

python
class Counter:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current < self.limit:
            self.current += 1
            return self.current
        else:
            raise StopIteration

counter = Counter(3)
for number in counter:
    print(number)
Output
1 2 3
⚠️

Common Pitfalls

Common mistakes include:

  • Not raising StopIteration in __next__, causing infinite loops.
  • Returning a new iterator in __iter__ each time, which can reset iteration unexpectedly.
  • Not implementing __iter__ at all, so the object is not iterable.
python
class WrongIterable:
    def __iter__(self):
        return self

    def __next__(self):
        return 1  # never raises StopIteration, infinite loop

# Correct way
class RightIterable:
    def __init__(self):
        self.count = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.count < 3:
            self.count += 1
            return self.count
        else:
            raise StopIteration
📊

Quick Reference

Summary tips to make an object iterable:

  • Implement __iter__ to return an iterator.
  • Iterator must implement __next__ to return next item or raise StopIteration.
  • Use for loops to automatically use these methods.
  • Reset iteration state carefully if needed.

Key Takeaways

Implement __iter__ to return an iterator object for your class.
The iterator must implement __next__ to provide items and raise StopIteration when done.
Without raising StopIteration, iteration will never stop and cause errors.
Use for loops to automatically iterate over your custom iterable objects.
Reset iteration state carefully if your object is reused in multiple loops.