How to pick just one item from a generator?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
To pick one item from a Python generator, use next(generator). This advances the generator to its first yield and returns the value. If the generator is exhausted, next() raises StopIteration — use next(generator, default) to return a default value instead. For picking a specific item, combine next() with itertools.islice() or a generator expression with a filter condition. The key advantage of using next() over converting to a list is that it does not consume the entire generator.
Basic: next()
Each call to next() advances the generator by one step. The generator retains its internal state between calls.
Handling Exhausted Generators
The two-argument form next(gen, default) returns the default when the generator has no more items, avoiding the need for try/except.
Pick the First Matching Item
The generator expression (x for x in gen if condition) is lazy — it only processes elements until the condition is met, then stops.
Pick the Nth Item with islice
islice(gen, start, stop) efficiently skips items without materializing them. It is the standard way to access a specific position in a generator.
Pick a Random Item
Reservoir sampling picks a uniformly random item from a generator of unknown length in a single pass with O(1) memory.
Pick Last Item
All methods consume the entire generator. deque(gen, maxlen=1) is the most memory-efficient — it discards all but the last element.
Pick Multiple Items
Common Pitfalls
- Converting to a list to pick one item:
list(generator)[0]works but consumes the entire generator into memory. For infinite generators, this hangs forever. Usenext(gen)instead — it only fetches one item. - Forgetting that generators are single-use: After calling
next()or iterating partially, you cannot restart a generator. To iterate again, create a new generator instance. Callingnext()on an exhausted generator raisesStopIteration. - Not providing a default to
next():next(gen)raisesStopIterationif the generator is empty. This is often unexpected. Usenext(gen, None)ornext(gen, default_value)to handle empty generators gracefully. - Using
next()inside aforloop on the same generator:for item in genandnext(gen)both advance the same generator. Mixing them causes skipped items. Use one approach consistently or be explicit about consuming items. - Assuming
islicereturns a generator:islicereturns anisliceiterator, not a list. To get a single value, wrap it innext():next(islice(gen, n, n+1)). Callinglist(islice(gen, n))returns a list of the first n items.
Summary
- Use
next(gen)to pick the first (or next) item from a generator - Use
next(gen, default)to avoidStopIterationon empty generators - Use
next(x for x in gen if condition)to find the first matching item - Use
itertools.islice(gen, n, n+1)to pick the nth item without consuming the whole generator - Use reservoir sampling for picking a random item from a generator of unknown length
- Generators are single-use and stateful —
next()advances them permanently
Related reading
- How to pickle Keras model?
- how to pip install 64 bit packages while having both 64 bit and 32 bit versions?
- How to pip install a package with min and max version range?
- How to pip install old version of librarytensorflow?
- How to plot a learning curve for a keras experiment?
- How to plot gradient descent using plotly
- How to plot grid of images in tensorboard?
- How to plot in multiple subplots
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.