Loading…
A short voice session: one question, one follow-up, then instant feedback — up to 5 minutes.
An iterable can produce an iterator through __iter__, like a list; an iterator returns items one at a time through __next__ and raises StopIteration when it is exhausted.
A for loop calls iter() on the object to get an iterator, then calls next() repeatedly until StopIteration. Lists, strings, dicts and files are iterables, and each call to iter(list) returns a fresh iterator, so a list can be looped many times. An iterator keeps its own position and is itself iterable, returning self from iter, but once exhausted it stays empty. Generators are a convenient way to create iterators. Understanding this explains why a generator or a zip object can be looped only once.