Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enumerate a list of non-string objects in Python?

There is a nice class Enum from enum, but it only works for strings. I'm currently using:

    for index in range(len(objects)):
        # do something with index and objects[index]

I guess it's not the optimal solution due to the premature use of len. How is it possible to do it more efficiently?

like image 644
Alex Avatar asked Jun 07 '09 15:06

Alex


People also ask

What is enumerate () function in Python?

Python enumerate() Function The enumerate() function takes a collection (e.g. a tuple) and returns it as an enumerate object. The enumerate() function adds a counter as the key of the enumerate object.

Can you enumerate a list in Python?

Instead of using the range() function, we can instead use the built-in enumerate() function in python. enumerate() allows us to iterate through a sequence but it keeps track of both the index and the element. The enumerate() function takes in an iterable as an argument, such as a list, string, tuple, or dictionary.

What is enumerate objects 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.

What does enumerating the string Python do enumerate Python?

Enumerating a String This gives you the character index and the character value, for every character in the string. If you have a string you can iterate over it with enumerate(string). The code output above shows both the index and the value for every element of the string.


1 Answers

Here is the pythonic way to write this loop:

for index, obj in enumerate(objects):
  # Use index, obj.

enumerate works on any sequence regardless of the types of its elements. It is a builtin function.

Edit:

After running some timeit tests using Python 2.5, I found enumerate to be slightly slower:

>>> timeit.Timer('for i in xrange(len(seq)): x = i + seq[i]', 'seq = range(100)').timeit()
10.322299003601074
>>> timeit.Timer('for i, e in enumerate(seq): x = i + e', 'seq = range(100)').timeit()
11.850601196289062
like image 66
Ayman Hourieh Avatar answered Nov 14 '22 21:11

Ayman Hourieh