How to Slice a Generator with islice in Python
Use itertools.islice to take the first n items from any iterable without materializing the whole sequence into a list.
Python code
12 linesfrom itertools import islice
def first_n(iterable, n):
"""Return the first n items from an iterable."""
return list(islice(iterable, n))
if __name__ == "__main__":
numbers = range(10, 100) # large iterable
result = first_n(numbers, 5)
print(result) # [10, 11, 12, 13, 14]
Output
[10, 11, 12, 13, 14]
How it works
The islice function works like a lazy slice: it consumes the iterable step-by-step and stops after n items, never building the entire sequence in memory. This is crucial for infinite generators and huge data streams. Here we wrap the result in list() to inspect the values, but in real code you can iterate over the islice object directly to keep memory usage flat. Because islice operates on the iterator protocol, it works with any iterable — lists, tuples, generators, file objects, or range.
Common mistakes
- Forgetting that `islice` consumes the original iterator, so reusing it later continues from where it left off.
- Using regular list slicing `iterable[:n]`, which only works on sequences, not generators.
- Wrapping the entire iterable in `list()` before slicing, which defeats the lazy benefit.
- Confusing `islice(iterable, n)` with `islice(iterable, start, stop)` where the second argument is a stop index.
Variations
- Use `itertools.islice(gen, 5)` directly in a loop without converting to a list to stream items.
- Use `list(itertools.islice(gen, 5))` to get a small list while skipping a lot of data with `islice(gen, start, stop)`.
Real-world use cases
- Streaming top N rows from a large CSV file or database cursor without loading the whole dataset into memory.
- Peeking at a few records from an infinite generator, like a live sensor feed or a message queue, for a quick sample.
- Reading the first lines of a log file line-by-line while ignoring the rest after the header.
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.