Take n items from an infinite Python generator
Uses itertools.islice to lazily take exactly n items from an infinite generator without exhausting it.
Python code
15 linesfrom itertools import islice
def count_up_from(start=0):
n = start
while True:
yield n
n += 1
def take_n(generator, count):
return list(islice(generator, count))
if __name__ == "__main__":
gen = count_up_from(10)
result = take_n(gen, 5)
print(result)
Output
[10, 11, 12, 13, 14]
How it works
count_up_from is an infinite generator that yields numbers starting at start. itertools.islice consumes the generator lazily, producing only the requested count of items. Returning a list materializes the slice, which is fine for small counts. The generator remains open for further iteration, making it ideal for infinite or large sequences.
Common mistakes
- Using a list comprehension over an infinite generator — never terminates
- Forgetting that islice stops at the given count, not at a stop index
- Not importing islice from itertools
- Assuming the generator is exhausted after taking items
Variations
- Use a for loop with `next()` and a break condition to collect items
- Use `enumerate` and break after n items
Real-world use cases
- Reading a fixed number of lines from an endless log stream
- Sampling a chunk of data from an infinite sequence like Fibonacci numbers
- Fetching a limited batch of results from a lazy database cursor
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.