Interview Questions
Iterators and Generators · Study material
Iterators and Generators – Interview Questions
1. What is the difference between an iterable and an iterator?
An iterable can produce an iterator (has __iter__); an iterator produces values one by one (has __next__) and remembers its position. Iterators are iterables that return themselves.
2. What does next() do?
Returns the next item from an iterator, or raises StopIteration (or returns a supplied default) when exhausted.
3. How does a for loop work internally?
It calls iter() on the iterable, then next() repeatedly until StopIteration, which it handles silently.
4. What is a generator?
An iterator created by a function containing yield (or by a generator expression), producing values lazily.
5. Difference between yield and return?
return ends the function with one value; yield produces a value and pauses, so the function can resume and produce more.
6. Why are generators memory-efficient?
They produce one value at a time instead of building the whole sequence in memory.
7. Can you iterate a generator twice?
No; once exhausted it yields nothing. Create a new generator or store the values in a list.
8. What does yield from do?
Yields every value of another iterable or generator, and returns that generator's return value.
9. What happens to a return value in a generator?
It is attached to StopIteration as .value.
10. What does send() do?
Resumes the generator and makes the current yield expression evaluate to the sent value.
11. How do you write an iterator class?
Define __iter__ returning self and __next__ returning the next value or raising StopIteration.
12. What is PEP 479?
Since Python 3.7, a StopIteration raised inside a generator is converted to RuntimeError, so bugs do not silently end iteration.
13. How do you take the first n items of an infinite generator?
itertools.islice(gen, n), or a loop with a counter and break.
14. Are range objects iterators?
No; range is an iterable sequence. iter(range(3)) gives an iterator, and range supports len() and indexing.
15. Name some useful itertools functions.
count, cycle, repeat, islice, chain, takewhile, dropwhile, groupby, accumulate, product, permutations, combinations.