Enumerate is a function that loops over an object (that’s iterable) and keeps track of how many times it has looped.
Alright, let’s simplify it:
What does Iterate mean? In mathematics, Iteration is the repetition of a process in order to generate a sequence of outcomes.
What is an Iterable? An iterable object in Python is an object capable of returning its data one by one.
There are two types of loops in python; while which loops while a certain condition is satisfied and for is similar to while, but executes for a certain amount of times.
You may be asking “Devisha, doesn’t for i in range(x) do the same thing?”. Not really; since if you use for i in range(x) and want to access an element i, you’ll have to do element[i]. But with for index, data in enumerate(x), you can get the data and the index at once.
How do you use enumerate?
When you declare a variable with enumerate (Eg: a = enumerate("aaa") ) and call it, it’ll return something like <enumerate object at 0x11009994>, which is the memory address of the function. So to get the items you’ll have to use a loop. such as for index, data in enumerate(x) . You can also use next(x) to get the next value of the enumerated list.
watchmen = ["John", "Walter", "Daniel", "Eddie", "Sally"]
for index, name in enumerate(watchmen):
print(f"{index}: {name}")In the above example, I’ve made a list object called “watchmen”, which contains the names of all the watchmen. for index, name in enumerate(watchmen): In this line, I declared two variables; index and name because enumerate splits the Object into two. the first being the index (0 onwards) and the second being the data. If you run the code, the output should be;
0: John
1: Walter
2: Daniel
3: Eddie
4: SallyAn Example With A While Loop
watchmen = ["John", "Walter", "Daniel", "Eddie", "Sally"]
enum = enumerate(watchmen)
while True:
try:
index, name = next(enum)
print(index, name, sep=": ")
except StopIteration:
breakThe while loop enumeration setup is a little more challenging to create than the for loop. As you can see, I’ve declared enum which is the enumerated object. During the while loop, I’ve setup two variables; index and name, which come from the function next(enum) . next() gives you the next iteration of the the enumerated object (works with generators as well). You would’ve noticed the try and except; I placed these because While True goes on forever, and enum doesn’t have enough terms to go on forever. When an enumerated object or a generator doesn’t have more data to provide (when calling next()) it raises a StopIteration exception. So the function of except is to stop the loop once it detects the exception.
Should You Replace for i in range(len(x)): With enumerate()
There are multiple good reasons to. The most important ones being:
- Code Tidying (Since its a lot shorter than
for i in range(len(x))) - Speed (By a small margin)
Conclusion
dog_breeds = ["Golden Retriever", "German Shepherd", "Bernese Mountain Dog", "St. Bernard"]
#---------- Getting data from a normal list ---------------
# Method One - Index Only
for i in range(len(dog_breeds)):
print(dog_breeds[i])
# Method Two - Value Only
for dog in dog_breeds:
print(dog)
# Method Three (never to rarely used)
i = 0
while True:
try:
print(dog[i])
i += 1
except IndexError:
break
# ------------ Getting Data using Enumerate ---------------
# (it's worth noting that if you don't want one of the two variables
# just replace it with a '_', which is a throwaway variable)
# Method One - next (data and index) [gives one element per call]
enum = enumerate(dog_breeds)
data = next(enum) # Data and index as a tuple => (0, 0)
id, data = next(enum) # id and data separately
# Method Two - for loop (data and index)
for i, dog in enumerate(dog_breeds):
print(dog)
# Method Three - while loop (data and index)
enum = enumerate(dog_breeds)
while True:
try:
index, name = next(enum)
print(name)
except StopIteration:
breakThat’s my article on enumerate, hope you enjoyed!