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, number in enumerate(numbers):
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

Numbering can also be set to begin at any desired number.

numbers = ["one", "two", "three", "four"]

for i, number in enumerate(numbers, 10):
print('index : {0} - number : {1}'.format(i, number))

# Output:
# index : 10 - number : one
# index : 11 - number : two
# index : 12 - number : three
# index : 13 - number : four

Thank you all :)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Said BADAOUI

Said BADAOUI

JavaScript || Reactjs || Nextjs || Nodejs || Python || Front-end Developer