Reputation: 17710
is there a simple way to stop an iterator after N
loops? Of course I can write something like:
for i, val in enumerate(gen()):
if i > N: break
but I would like to write something like
for val in stop_after(gen(), N):
...
I tried with itertools.dropwhile
but it seems to do the opposite. Of course I can rewrite itertools.dropwhile
with the inverse logic, but I am wondering if there is something already implemented.
Upvotes: 1
Views: 620
Reputation: 74655
Use islice
:
for val in itertools.islice(gen(), N):
....
Assuming that your example was meant to be:
for i, val in enumerate(gen()):
if i > N: break
Upvotes: 2
Reputation: 10145
I think you need itertools.takewhile
:
https://docs.python.org/2/library/itertools.html#itertools.takewhile
Upvotes: 0