Wednesday, June 18, 2025

How can you make an object iterable in Python?

All Questions From This Chapter

Make an object iterable

To make an object iterable in Python, you need to implement either:


✅ Option 1: __iter__()

The simplest and most common way is to define an __iter__() method that returns an iterator (usually self or a generator).

Example:

python
class MyIterable: def __init__(self, data): self.data = data def __iter__(self): return iter(self.data) # delegates to the iterable data obj = MyIterable([1, 2, 3]) for item in obj: print(item)

✅ Option 2: __getitem__() (legacy approach)

If your object implements __getitem__() and raises IndexError when the sequence ends, it is implicitly iterable.

Example:

python
class MyIterable: def __init__(self, data): self.data = data def __getitem__(self, index): return self.data[index] obj = MyIterable([10, 20, 30]) for item in obj: print(item)

Python internally tries to call obj[0], obj[1], ... until IndexError is raised.


🧠 Summary:

MethodRequired?Purpose
__iter__()YesReturns an iterator for your object
__next__()OptionalNeeded if your class is also the iterator
__getitem__()LegacyAllows iteration without __iter__()

Best practice: Prefer __iter__() + generators for clean, efficient code.

Tags: Python,Interview Preparation,Technology,

No comments:

Post a Comment