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?
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.
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 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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With