Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Iterator returning multiple values

class SquareCounter():
   def __init__(self):
       self.count = 0

   def __iter__(self):
       return self

   def __next__(self):
       self.count += 1
       if self.count > 5:
           raise StopIteration
       return self.count, self.count ** 2

for cnt, sqr in SquareCounter():
   print(f"{cnt}  {sqr}")

Output:

1  1
2  4
3  9
4  16
5  25