Proposal: Add a `limit` parameter to `enumerate()`

I propose adding an optional limit parameter to the built-in enumerate() function to restrict the number of iterations.

Limiting iteration is a common task, but current solutions are verbose:

# Current approach: requires import and nesting
from itertools import islice

for i, item in islice(enumerate(data), 5):
    ...

Alternatives have downsides: slicing creates copies, and zip(range(n), data) ignores the start parameter.

Update the signature to: enumerate(iterable, start=0, limit=None)

Examples:

# Stop after 10 items
for i, line in enumerate(file, limit=10):
    print(i, line)
# Works with start
for i, item in enumerate(data, start=1, limit=3):
    print(i, item)

It makes a common pattern more readable and removes the need for itertools.islice in simple loops.

Thoughts?

You could zip(range(start, start+n), data) perhaps?

2 Likes

No thanks. Enumerate is for enumerating, not limiting anything regarding the length of the iteration.

If anything, we should add itertools with clearer intent for take, skip, step_by, nth, sllice, which are all things that islice can do but are verbose to do.

But a parameter on an unrelated iterator? At that point just add everuthing as parameters to map (or worse, find a way to add even more new special syntax to comprehensions)

1 Like