Skip to content
Advertisement

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.

JavaScript

I can’t think of a nicer way, but maybe there is? Maybe a functional form?

Advertisement

Answer

Use itertools.islice():

JavaScript

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

Advertisement