Why use enumerate() instead of range() in your python's loops
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().
The range()
function is often useful when iterating over a set of integers:
for n in range(200):
print(n)
#
for n in range(50, 110):
print(n)
or a list of strings:
for number in ["one", "two", "three", "four"]:
print(number)
Now, say you want to iterate over the list of numbers and also show the index of the current item in the list. Using range()
, this might be done like this:
numbers = ["one", "two", "three", "four"]
for i in range(len(numbers)):
number = numbers[i]
print('index : {0} - number : {1}'.format(i, number))
# Output:
# index : 0 - number : one
# index : 1 - number : two
# index : 2 - number : three
# index : 3 - number : four
It gets the job done, but not very pythonic. You have to get the length of the list to keep track of the index, then index into the array to get the current fruit — which makes the code more verbose and harder to read.
That’s why enumerate()
is the better way
numbers = ["one", "two", "three", "four"]
for i…