Python28 min read

Python Iterators and Iterables

Master iterables and iterators: understand __iter__ and __next__, build custom iteration like Fibonacci, and learn how for-loops really work.

David Miller
August 11, 2025
10.9k475

A lot of Python power comes from iteration.

      When you write:
      `for x in something:`
      Python is using the iterator protocol behind the scenes.
      
      ## Definitions (clear and simple)
      
      - **Iterable**: an object you can loop over (it has __iter__)
      - **Iterator**: an object that returns values one by one (it has __next__)
      
      Many objects (like lists) are iterables, but not iterators.
      
      ## Example: list is iterable
      
      ```python
      nums = [1, 2, 3]
      it = iter(nums)
      
      print(next(it))
      print(next(it))
      print(next(it))
      ```
      
      Expected output:
      ```
      1
      2
      3
      ```
      
      ## Custom iterator (Counter)
      
      ```python
      class Counter:
          def __init__(self, max_value):
              self.max_value = max_value
              self.current = 0
      
          def __iter__(self):
              return self
      
          def __next__(self):
              if self.current < self.max_value:
                  self.current += 1
                  return self.current
              raise StopIteration
      
      for n in Counter(5):
          print(n)
      ```
      
      ## Fibonacci iterator (classic interview + real use)
      
      ```python
      class Fibonacci:
          def __init__(self, count):
              self.count = count
      
          def __iter__(self):
              self.a, self.b = 0, 1
              self.i = 0
              return self
      
          def __next__(self):
              if self.i >= self.count:
                  raise StopIteration
              value = self.a
              self.a, self.b = self.b, self.a + self.b
              self.i += 1
              return value
      
      for n in Fibonacci(10):
          print(n)
      ```
      
      ## How a for-loop works internally (simplified)
      
      ```python
      # Python roughly does:
      iterator = iter(iterable)
      while True:
          try:
              item = next(iterator)
              # body
          except StopIteration:
              break
      ```
      
      ## Graph: iteration pipeline
      
      ```mermaid
      flowchart LR
        A[Iterable] --> B[iter()]
        B --> C[Iterator]
        C --> D[next()]
        D --> E[Value]
        D --> F[StopIteration when done]
      ```
      
      ## Key points
      
      - Iterable gives an iterator
      - Iterator produces values with next()
      - for loop stops on StopIteration
      - Custom iterators can model streaming data
      
#Python#Advanced#Iterators