title: Python: Why is the __len__() of a sequence ignored when iterating?
body: <p>I'd like to create a custom sequence of elements. When iterating over it, the length of the sequence is ignored. Here is a minimal code example:</p>
  
  <pre><code>class Test():
      def __init__(self):
          pass
  
      def __len__(self):
          return 5
  
      def __getitem__(self, idx):
          return idx
  
  t = Test()
  for i, x in enumerate(t):
      print(i, x)
  </code></pre>
  
  <p>I'd expect to have only <code>0 0</code> to <code>4 4</code> printed out. In reality, the loop behaves as with an infinitely long sequence and goes on and on and on. <code>len(t)</code> returns <code>5</code> as expected.</p>
  
  <p>What am I missing?</p>