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:
✅ Option 2: __getitem__()
(legacy approach)
If your object implements __getitem__()
and raises IndexError
when the sequence ends, it is implicitly iterable.
Example:
Python internally tries to call
obj[0]
,obj[1]
, ... untilIndexError
is raised.
🧠Summary:
Method | Required? | Purpose |
---|---|---|
__iter__() | Yes | Returns an iterator for your object |
__next__() | Optional | Needed if your class is also the iterator |
__getitem__() | Legacy | Allows iteration without __iter__() |
✅ Best practice: Prefer __iter__()
+ generators for clean, efficient code.
No comments:
Post a Comment