Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only index needed: enumerate or (x)range?

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     
like image 951
LarsVegas Avatar asked Aug 10 '12 11:08

LarsVegas


People also ask

Should I use enumerate or range?

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.

Should I use enumerate?

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.

What is the use of enumerate () function?

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.

Is enumerate faster than for loop?

Using enumerate() is more beautiful but not faster for looping over a collection and indices.


1 Answers

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...

like image 58
Jon Clements Avatar answered Oct 30 '22 01:10

Jon Clements