Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 507
Alfe Avatar asked Nov 11 '14 11:11

Alfe


People also ask

Which function is used to get an iterator to the first element?

begin() function is used to return an iterator pointing to the first element of the map container.

What is Islice?

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.

Can you slice a generator?

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.


2 Answers

Use itertools.islice():

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

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

like image 135
Martijn Pieters Avatar answered Sep 21 '22 01:09

Martijn Pieters


Without using itertools:

(t[0] for t in zip(L, range(3)))
like image 35
6502 Avatar answered Sep 22 '22 01:09

6502