Enumerate helps to track the index and element. Though we can gain the same feature using for loop but enumerate makes the code more readable
Imagine we have a list of colors color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown','Cyan'] For tracking both the index and corresponding element we can write this simple code
An Example Without Enumerate
color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
#Without enumerate Manually track index using a counter variable
index = 0
for color in color_names:
print(f"Color {index}: {color}")
index += 1
We can achieve the same thing with Enumerate. Best thing is it increase the readability and you do not have to track the indexing manually.
The Same Example With Enumerate
color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown','Cyan']
for index, color in enumerate(color_names):
print(f"Color {index}: {color}")
This will show the index color name
Color 0: Red
Color 1: Orange
Color 2: Yellow
Color 3: Green
Color 4: Blue
Color 5: Purple
Color 6: Pink
Color 7: Brown
Color 8: Cyan
There are some more details example where you can enumerate. Also I have embedded an online browser based python interpreter( at the end of the article) so you can test the code here instantly
Apply Condition to Access The Index And Value efficiently
In Python programming, accessing both the index and the corresponding value from a list simultaneously, especially with certain conditions, is a common task. Get both the index and value from a Python list more easier with enumerate.
color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
for index, color in enumerate(color_names):
if index % 2 == 0:
print(f"Color {index}: {color}")
Color 0: Red
Color 2: Yellow
Color 4: Blue
Color 6: Pink
Color 8: Cyan
Update Elements of a List
Updating list items by their index offers a flexible way to make changes to your data. In the example We changed all the color names to uppercase.
color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
for index, color in enumerate(color_names):
if index % 2 != 0:
color_names[index] = color.upper()
print(color_names)
['Red', 'ORANGE', 'Yellow', 'GREEN', 'Blue', 'PURPLE', 'Pink', 'BROWN', 'Cyan']
Creating python Dictionaries
Transform lists into dictionaries for faster data lookup and better organization. Easily organize and find your data by turning lists into dictionaries using enumerate.
color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
color_dict = {index: color for index, color in enumerate(color_names)}
print(color_dict)
{0: 'Red', 1: 'Orange', 2: 'Yellow', 3: 'Green', 4: 'Blue', 5: 'Purple', 6: 'Pink', 7: 'Brown', 8: 'Cyan'}
Accessing Items from Two Lists Together
Process information from several lists at once for more efficient programming.
color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
rgb_values = [(255, 0, 0), (255, 165, 0), (255, 255, 0), (0, 128, 0), (0, 0, 255), (128, 0, 128), (255, 192, 203), (165, 42, 42), (0, 255, 255)]
for index, (color, rgb) in enumerate(zip(color_names, rgb_values)):
print(f"Color {index}: {color}, RGB: {rgb}")
for index, color in enumerate(random_color_names):
print(f"Color {index}: {color}")
Color 1: Red, RGB: (255, 0, 0)
Color 2: Orange, RGB: (255, 165, 0)
Color 3: Yellow, RGB: (255, 255, 0)
Color 4: Green, RGB: (0, 128, 0)
Color 5: Blue, RGB: (0, 0, 255)
Color 6: Purple, RGB: (128, 0, 128)
Color 7: Pink, RGB: (255, 192, 203)
Color 8: Brown, RGB: (165, 42, 42)
Color 9: Cyan, RGB: (0, 255, 255)
Indexed List and Create Tuples
Python's enumerate function typically starts counting at 0 (like most programming tools). But, by setting start=1, we can make our lists match how people normally count, making them easier to read. We're creating indexed_colors, a list of tuples where each tuple holds an index (starting from 1) and its corresponding color. Tuples are immutable (meaning their contents can't change), ensuring our color references stay organized.
color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
indexed_colors = list(enumerate(color_names, start=1))
print(indexed_colors)
[(1, 'Red'), (2, 'Orange'), (3, 'Yellow'), (4, 'Green'), (5, 'Blue'), (6, 'Purple'), (7, 'Pink'), (8, 'Brown'), (9, 'Cyan')]
Apply Condition to skip the elements.
Skip items when looping if they meet specific conditions. This makes your code more adaptable
color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
for index, color in enumerate(color_names):
if 'e' in color:
continue
print(f"Color {index}: {color}")
Color 6: Pink
Color 7: Brown
Color 8: Cyan
Working With Files
Working with files? Python's enumerate function makes it easy to read and process each line, keeping your code clean and efficient.
with open('text.txt', 'r') as file:
for line_number, line_content in enumerate(file, start=1):
print(f"Line {line_number}: {line_content.strip()}")
Working with List Comprehensions
List comprehensions are a short and clear way to create new lists in Python. They let you quickly transform one list into another. You can use the enumerate() function with list comprehensions to easily add indexes to your new lists. This makes your code easier to read and write.
color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
indexed_colors = [(index, color) for index, color in enumerate(color_names)]
print(indexed_colors)
[(0, 'Red'), (1, 'Orange'), (2, 'Yellow'), (3, 'Green'), (4, 'Blue'), (5, 'Purple'), (6, 'Pink'), (7, 'Brown'), (8, 'Cyan')]
Reverse a List
To reverse a list and enumerate its elements simultaneously, Python offers an elegant solution: combine enumerate(), reversed(), and list comprehension
color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
reversed_colors = [(index, color) for index, color in enumerate(reversed(color_names))]
print(reversed_colors)
[(0, 'Cyan'), (1, 'Brown'), (2, 'Pink'), (3, 'Purple'), (4, 'Blue'), (5, 'Green'), (6, 'Yellow'), (7, 'Orange'), (8, 'Red')]