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?
begin() function is used to return an iterator pointing to the first element of the map container.
islice(iterable, start, stop[, step]) Make an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped.
Iterators and generators can't normally be sliced, because no information is known about their length (and they don't implement indexing). The result of islice() is an iterator that produces the desired slice items, but it does this by consuming and discarding all of the items up to the starting slice index.
Use itertools.islice()
:
from itertools import islice
print(list(islice(it, 3)))
This will yield the next 3 elements from it
, then stop.
Without using itertools
:
(t[0] for t in zip(L, range(3)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With