__iter__

Dunder MethodPython 2.0+Intermediate

Returns an iterator; makes the object usable in for loops

Quick Info

Documentation
Official Docs
Python Version
2.0+

Learn by Difficulty

Quick Example

python
class Countdown:
    def __init__(self, start):
        self.start = start

    def __iter__(self):
        n = self.start
        while n > 0:
            yield n
            n -= 1

for num in Countdown(5):
    print(num)

__iter__ returns an iterator; makes the object usable in for loops. Implementing it lets you customize how Python interacts with your objects.

Try in Playground

Tags

oopmagic-methodprotocolcore