Назад к подготовке
ВопросСредняяpython-runtimeСобеседование · Navio

Вопрос

What happens under the hood in a Python for-loop? How do iterators and generators differ, and what is StopIteration?

Ответить самому

Сначала сформулируйте ответ как на собеседовании, затем откройте разбор и оцените себя.

Загрузка

Короткий ответ

A for-loop calls iter(obj), then repeatedly calls next(iterator) until StopIteration. Generators are iterator objects produced by functions containing yield and have extra coroutine-style methods.

Полный разбор

In a for-loop, Python first obtains an iterator by calling iter(obj). Then it repeatedly calls next(iterator). When the iterator has no more values, it raises StopIteration, and the loop exits normally.

An iterator is any object implementing the iterator protocol: __iter__ returns the iterator, and __next__ returns the next value or raises StopIteration. A generator is a convenient way to create such an object with a function that uses yield. Each yield pauses the function and preserves its local state until the next call.

Generators are also more than just a syntax shortcut. Generator objects support methods such as send, throw and close, which is why they can be used as coroutine building blocks. In ordinary interview answers, the important baseline is still the iter/next/StopIteration protocol.

Теория

Iteration in Python is protocol-based, not limited to built-in collections.

Типичные ошибки

  • Say a generator returns a full list.
  • Forget StopIteration.
  • Assume __iter__ and __next__ are only for built-in objects.

Как отвечать на собеседовании

  • Write the desugared while-loop in words.
  • Mention yield preserves state between next calls.