If I want to use only the index within a loop, should I better use the range/xrange
function in combination with len()
a = [1,2,3] for i in xrange(len(a)): print i
or enumerate
? Even if I won't use p
at all?
for i,p in enumerate(a): print i
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.
You should use enumerate() anytime you need to use the count and an item in a loop. Keep in mind that enumerate() increments the count by one on every iteration. However, this only slightly limits your flexibility. Since the count is a standard Python integer, you can use it in many ways.
Definition and Usage 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.
Using enumerate() is more beautiful but not faster for looping over a collection and indices.
I would use enumerate
as it's more generic - eg it will work on iterables and sequences, and the overhead for just returning a reference to an object isn't that big a deal - while xrange(len(something))
although (to me) more easily readable as your intent - will break on objects with no support for len
...
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