with open('/etc/passwd') as f:
while True:
line = next(f, None)
if line is None:
break
print(line, end='')
items = [1, 2, 3]
Get the iterator
it = iter(items) # Invokes items.iter()
Run the iterator
next(it) # Invokes it.next()
1
next(it)
2
next(it)
3
next(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
class Node: def init(self, value): self._value = value self._children = []
def __repr__(self):
return 'Node({!r})'.format(self._value)
def add_child(self, node):
self._children.append(node)
def __iter__(self):
return iter(self._children)
if name == 'main': root = Node(0) child1 = Node(1) child2 = Node(2) root.add_child(child1) root.add_child(child2) # Outputs Node(1), Node(2) for ch in root: print(ch