Python enumerate() function makes it easy to keep track of both the items in a sequence (like a list) and their positions (indexes) as you go through them. It’s like adding a built-in counter to your loops, making it convenient when you need to know where each item is located within the sequence.
enumerate()
Syntax
You call the enumerate() function and pass in the iterable you want to loop over. By default, it starts counting from zero, but you can change that by adding a start argument and setting it to the number you want to begin with. Here’s how it looks: enumerate(iterable, start=0)
. The iterable can be any object that supports iteration, such as a list, tuple, or string.
for index, item in enumerate(iterable, start=0):
# ... your code here
for index, item in ...
: The usual structure of a for loop in Python, but now it unpacks tuples fromenumerate
.enumerate(iterable, start=0)
: Theenumerate()
function itself.iterable
: The sequence (list, tuple, string, etc.) you want to loop through.start
(optional): The starting value for the index (defaults to 0).
Example 1: Python enumerate()
Let’s say you have a list of fruits: fruits = ['apple', 'banana', 'orange']
. If you use Python enumerate()
, you’ll get pairs of (index, fruit) on this list. For example, the first pair will be (0, ‘apple’), the second will be (1, ‘banana’), and so on. You can see how it pairs the index with the corresponding item in the list. This is shown in the following code:
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(f"Fruit at index {index}: {fruit}")
Code Explanation
- Line 1: Defines a list of fruits.
- Line 2: Loops through the
fruits
list, getting both the index and the fruit itself on each iteration. - Line 3: Prints the index and the corresponding fruit.
Output
Fruit at index 0: apple
Fruit at index 1: banana
Fruit at index 2: orange
Example 2: Loop Over an Enumerate Object
Python enumerate() creates a special “enumerate object” with index-value pairs. You can then use a for loop to go through this object. In each step of the loop, you get a tuple containing the index and the corresponding value from your original list or iterable. This allows you to work with the position and the element within your loop.
fruits = ["apple", "banana", "orange"]
enum_obj = enumerate(fruits)
for item in enum_obj:
print(item)
Code Explanation
- Line 1: Defines a list of fruits
- Line 2: Creates an enumerate object from the list
- Line 3: Iterates over the enumerate object, where each
item
is a tuple containing the index and the value from the list - Line 4: Prints each tuple
Output
(0, ‘apple’)
(1, ‘banana’)
(2, ‘orange’)
Example 3: Access the Next Element
You’re always working with the current element when looping through a sequence. To “access the next element,” generally, you’d need to look ahead in the sequence, which can be tricky. However, enumerate() provides the index, which you could use to calculate and access the index of the next element if needed, keeping in mind potential errors if you try to access an index that doesn’t exist.
fruits = ["apple", "banana", "orange"]
enum_obj = enumerate(fruits)
print(next(enum_obj))
print(next(enum_obj))
Code Explanation
- Line 1: Defines a list of fruits
- Line 2: Creates an enumerate object from the list
- Line 4: Uses the
next()
function to access the next element in the enumerate object, which is a tuple containing the index and the value- Prints the next tuple
Output
(0, ‘apple’)
(1, ‘banana’)
Example 4: Custom Start Index
One of the cool features of Python enumerate() is that you can tell it where to start counting. Instead of the default 0, you can give it any number. This is useful when you want your output to start from a different number, like 1. Add start=1
(or any other number) to the enumerate() function.
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits, start=1):
print(f"Fruit #{index}: {fruit}")
Same as the first example but starts the index at 1 instead of the default 0.
Output
Fruit #1: apple
Fruit #2: banana
Fruit #3: orange