CKTIS / Python
object.__iter__
The iteration method returns an iterator over the object’s elements.
Version: Python 3.14; repository image, production runtime not attested
Syntax
it = iter(container)The iteration method returns an iterator over the object’s elements.
object.__iter__
A reusable container normally returns a fresh iterator, whereas an iterator returns itself. Returning a list directly from this method raises TypeError because a list is not an iterator.
The two Shelf iterators have independent positions, so the second still yields a after the first yields a and b.
class Bad:
def __iter__(self): return [1]
try: iter(Bad())
except TypeError: pass
else: raise AssertionError
it=iter([1])
assert iter(it) is it
Examples
class Shelf:
def __init__(self, names): self.names = names
def __iter__(self): return iter(self.names)
s=Shelf(["a","b"])
a,b=iter(s),iter(s)
print(next(a), next(a), next(b), list(s))
Result
a b a ['a', 'b']
The two Shelf iterators have independent positions, so the second still yields a after the first yields a and b.