Python core · Concept
Iterables, iterators and generators
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
What's the difference between an iterable, an iterator and a generator? What actually happens when a for loop runs?
Then
Follow-ups the interviewer asks next
- Write a class-based iterator over a date range, then the same as a generator.
- Why does looping over the same generator twice give nothing the second time?
- What does
yield fromadd over a loop withyield? - What happens if a generator reads a file and you stop halfway?
The answer
What a strong answer covers
- An iterable has
__iter__returning an iterator; an iterator has__next__(raisingStopIterationat the end) and__iter__returning itself. forcallsiter()once, thennext()untilStopIteration.- A generator is an iterator made by a function with
yield; its state pauses betweennext()calls, so it's lazy and single-pass. yield fromdelegates to another iterable and passessend()/throw()through.StopIterationraised inside a generator becomesRuntimeError(PEP 479).- Stopping early: the generator is closed when garbage-collected (or with
.close()), which runs itsfinally/withcleanup. - itertools:
islice,chain,groupby(needs sorted input),batched(3.12).
The red pen
Common traps
Avoid:"a generator is a function that returns a list"; not knowing generators are exhausted after one pass.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.