Repaso
EspaƱol
PythonIntermediatePY-28

Which methods make an object an iterator?

Options

  1. __len__ and __getitem__, which allow indexing and length
  2. __iter__ and __next__, with StopIteration raised at the end (Correct option)
  3. __enter__ and __exit__, which handle setup and cleanup
  4. __call__ and __next__, which allow calling and advancing

Answer

__iter__ and __next__ (raising StopIteration at the end)

Why

An iterator is an object that gives you the next value each time you call next() on it.

It needs __next__ (return the next value, or raise StopIteration when there are no more) and __iter__ (return itself).

A for loop calls these methods for you behind the scenes.

Remember

Iterator = __iter__ + __next__.

Key terms

Practice this question in Repaso