Note
Python - enumerate() - Count while iterating
Overview of the Python enumerate() function. Simplify counting while iterating over your object.
enumerate(iterable, start=0) is a built-in method that simply adds a counter to your iterable object and returns it as
an enumerate object.
iterable: The object to iterate over (e.g., list, tuple, or string).
start (optional): The starting value of the counter (default is 0).
This is especially helpful when you need to keep track of the index while iterating over an iterable.
Take a look at examples below:
few_letters = ["a", "b", "c"]
for index, letter in enumerate(few_letters):
print(index, letter)
Output:
0 a
1 b
2 c
Returned enumerate object yields a pair of objects (that are being unpacked with index, letter in our example).
Changing the Starting Index
It is also possible to provide a start argument to change the default value of 0:
few_letters = ["a", "b", "c"]
for index, letter in enumerate(few_letters, start=1):
print(f"Number: {index} | Letter: {letter}")
Output:
Number: 1 | Letter: a
Number: 2 | Letter: b
Number: 3 | Letter: c
Using enumerate() Without Immediate Unpacking
Bear in mind that you are not forced to unpack the object immediately. You can as well do something like this if you have a reason:
few_letters = ["a", "b", "c"]
for element in enumerate(few_letters, start=1):
print(f"{element} - {type(element)}")
Output:
(1, 'a') - <class 'tuple'>
(2, 'b') - <class 'tuple'>
(3, 'c') - <class 'tuple'>
Key Points to Remember about the enumerate() Function
-
Simplicity:
enumerate()simplifies the process of keeping track of counting while iterating. -
Custom Start Value: The start argument allows you to set the initial counter value.
-
Versatility: You can unpack the
enumerateobject immediately in the loop or use it as needed.
I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!
You might also be interested in:
- 💡 Python - count() - Count occurrences of an element in a collection
- 💡 Python - chain() - Join multiple iterables lazily
- 💡 Python - Default Dict - Simplify handling of missing keys in dictionaries
- 💡 Python - zip_longest() - Combine iterables and fill missing values
- 💡 Python - Magic Method __eq__ - Implement custom object comparison