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.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 11 views 0 copies

Python code

12 lines
Python 3.9+
def 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

stdout
[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

  1. Use `itertools.islice(items, n, None)` to skip the first n items in a single call.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.