Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to include a stop parameter in enumerate python?

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

like image 551
Tom Smith Avatar asked Feb 11 '14 00:02

Tom Smith


People also ask

Is enumerate or range faster?

enumerate() is faster when you want to repeatedly access the list/iterable items at their index. When you just want a list of indices, it is faster to use len() and range().

What does enumerate () do in Python?

What does enumerate do in Python? The enumerate function in Python converts a data collection object into an enumerate object. Enumerate returns an object that contains a counter as a key for each value within an object, making items within the collection easier to access.

Is enumerate slower than for loop?

Initial googling got me the answer enumerate was faster than range. Reason : for loop via range just creating a proxy index i and when accessing the list data extra operations are carried to get the data at that index. Enumerate is implemented as a python iterator.

Is enumerate lazy?

The enumerate and reversed functions return iterators. Files in Python are also iterators. All of these iterators act like lazy iterables. They don't do any work, until you start looping over them.


2 Answers

for i, row in enumerate(myiterable[2:], start=2):
   if i>= limit: break
   ...

or

for i,row in itertools.takewhile(lambda (i,val):i < limit,enumerate(myiterable[2:],2)):

to rephrase the other suggestion (note that it will only work if your iterable is a sliceable object)

start,stop = 11,20
my_items = range(100)
for i,row in enumerate(my_items[start:stop],start):
      ....
like image 191
Joran Beasley Avatar answered Oct 02 '22 18:10

Joran Beasley


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
like image 36
Bi Rico Avatar answered Oct 02 '22 17:10

Bi Rico