How can I get the first n elements of an iterator (generator) in the simplest way? Is there something simpler than, e. g.
JavaScript
x
6
1
def firstN(iterator, n):
2
for i in range(n):
3
yield iterator.next()
4
5
print list(firstN(it, 3))
6
I can’t think of a nicer way, but maybe there is? Maybe a functional form?
Advertisement
Answer
Use itertools.islice()
:
JavaScript
1
3
1
from itertools import islice
2
print(list(islice(it, 3)))
3
This will yield the next 3 elements from it
, then stop.