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

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -