Search code examples
pythoniteratorgenerator

Simplest way to get the first n elements of an iterator


How can I get the first n elements of an iterator (generator) in the simplest way? Is there something simpler than, e. g.

def firstN(iterator, n):
  for i in range(n):
    yield iterator.next()

print list(firstN(it, 3))

I can't think of a nicer way, but maybe there is? Maybe a functional form?


Solution

  • Use itertools.islice():

    from itertools import islice
    print(list(islice(it, 3)))
    

    This will yield the next 3 elements from it, then stop.