Take n items from an infinite Python generator

Uses itertools.islice to lazily take exactly n items from an infinite generator without exhausting it.

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

Python code

15 lines
Python 3.9+
from 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

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

  1. Use a for loop with `next()` and a break condition to collect items
  2. 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

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.