Drop n items then yield rest generator
A generator that skips the first n items of an iterable and then yields the remaining items one by one.
Python code
12 linesdef drop(n, items):
"""Yield every item except the first n from items."""
it = iter(items)
for _ in range(n):
next(it, None) # skip first n items
yield from it
if __name__ == "__main__":
numbers = [10, 20, 30, 40, 50]
result = list(drop(2, numbers))
print(result)
Output
[30, 40, 50]
How it works
The drop function converts the input iterable into an iterator and then advances it n times using next(it, None), which safely skips items even if the iterable is shorter than n. After that, yield from it lazily yields all remaining items. Since it is a generator, the skipping happens on demand when the caller iterates, making it memory-friendly for large inputs.
Common mistakes
- Using `next(it)` without a default, which raises StopIteration when the iterable is shorter than n.
- Trying to slice a generator directly (e.g., `items[n:]`) which only works on sequences.
- Assuming `drop` modifies the original iterable, when it actually returns a new generator.
Variations
- Use `itertools.islice(items, n, None)` to skip the first n items in a single call.
- Use a list comprehension with a slice for simple sequences: `[x for x in items[n:]]` (not lazy).
Real-world use cases
- Skipping header rows in a CSV file before processing data rows.
- Ignoring the first few log lines that contain test/startup messages in a log parser.
- Sampling data after a warm-up phase in performance benchmarks.
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.