python - Simplest way to get the first n elements of an iterator -
how can first n elements of iterator (generator) in simplest way? there simpler than, e. g.
def firstn(iterator, n): in range(n): yield iterator.next() print list(firstn(it, 3)) i can't think of nicer way, maybe there is? maybe functional form?
use itertools.islice():
from itertools import islice print list(islice(it, 3)) this'll yield next 3 elements it, stop.
Comments
Post a Comment