Search code examples
pythongeneratorpython-itertools

opposite of itertools.dropwhile (how to stop generators after N iteration)


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.


Solution

  • 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