An iterator convention lets objects supply successive values to for loops and many functions. An iterable implements __iter__, which returns an iterator; that iterator implements __next__ and raises StopIteration when exhausted. section 11.1 section 11.5
A for loop calls iter on its target, repeatedly calls next on the returned iterator, and stops when StopIteration is raised. The object controls what each iteration produces: strings yield characters, dictionaries yield keys, and files yield lines. section 11.2
Implement the convention in three practical ways:
- Add __iter__ and __next__ to a class, storing iteration state such as the current index on the object. section 11.7
- Separate an iterable from a helper iterator when the same object should support independent, repeatable loops. section 11.7
- Use generator functions or generator expressions when they express the iteration more directly or avoid constructing a full list. section 11.26 section 11.27
Repeating values with a custom iterator
A Circle object can return elements from a sequence a specified number of times, repeating the sequence as necessary. For example, list(Circle('abc', 5)) produces five values before the iterator ends. section 11.10
for i in 'abcd':
print(i) #1
A short for-loop example makes the protocol’s user-facing behavior concrete before implementation details are introduced. section 11.1














