Easiest way to include a stop parameter in enumerate python?

Tom Smith picture Tom Smith · Feb 11, 2014 · Viewed 10.7k times · Source

Ss there a simple way to iterate over an iterable object that allows the specification of an end point, say -1, as well as the start point in enumerate. e.g.

for i, row in enumerate(myiterable, start=2): # will start indexing at 2

So if my object has a length of 10, what is the simplest way to to get it to start iterating at index 2 and stop iterating at index 9?

Alternatively, is there something from itertools that is more suitable for this. I am specifically interested in high performance methods.

In addition, when the start option was introduced in 2.6, is there any reason why a stop option was not?

Cheers

Answer

Bi Rico picture Bi Rico · Feb 11, 2014

I think you've misunderstood the 'start' keyword, it doesn't skip to the nth item in the iterable, it starts counting at n, for example:

for i, c in enumerate(['a', 'b', 'c'], start=5):
    print i, c

gives:

5 a
6 b
7 c

For simple iterables like lists and tuples the simplest and fastest method is going to be something like:

obj = range(100)
start = 11
stop = 22
for i, item in enumerate(obj[start:stop], start=start):
    pass