Python enumerate() Function
The enumerate() function adds a counter to an iterable. It is a built-in function that allows you to iterate over a list or other iterable object, while keeping track of the index of the current item. It returns an enumerate object, which is an iterator that generates pairs containing the index and the value of each element of the iterable. Syntax:
enumerate(iterable, start=0)
- iterable - a sequence or objects that support iteration.
- start - (optional) start counting from this value .
for index, value in enumerate(iterable, start=1):
# do something with index and value
- iterable - a sequence or objects that support iteration.
- value - (optional) start counting from this value .
This will start counting from 1 instead of 0.
Python Enumerate | Examples
colors = ["Red", "Blue", "Green"]
clObj = enumerate(colors)
print (list(enumerate(colors)))
//Output: [(0, 'Red'), (1, 'Blue'), (2, 'Green')]
print ("Return type:", type(colors))
//Output: Return type: <class 'list'>
Changing starting index of Enumerate
colors = ["Red", "Blue", "Green"]
print (list(enumerate(colors, 5)))
//Output: [(5, 'Red'), (6, 'Blue'), (7, 'Green')]
Using Enumerate object in loops:

colors = ["Red", "Blue", "Green"]
for cl in enumerate(colors):
print (cl)
//Output:
(0, 'Red')
(1, 'Blue')
(2, 'Green')
Changing index in for loop
colors = ["Red", "Blue", "Green"]
for cnt, cl in enumerate(colors, 55): # index start from 55
print (cnt, cl)
//Output:
55 Red
56 Blue
57 Green
Enumerating a String
str = "python"
for cnt,cl in enumerate(str):
print (cnt,cl)
//Output:
0 p
1 y
2 t
3 h
4 o
5 n
Enumerating a Tuple
colors = [(100,"Red"), (200,"Blue"), (300,"Green")]
for cnt,cl in enumerate(colors):
print (cnt,cl)
//Output:
0 (100, 'Red')
1 (200, 'Blue')
2 (300, 'Green')
Python Enumerate Vs Python For Loops
Python enumerate() is a function that provides the index of the current element along with its value, while a for loop simply allows you to iterate over the elements in a sequence and perform a specific action for each element. Both can be used to iterate over a sequence but the enumerate function gives you access to the index of the current element, which can be useful in certain situations.
Related Topics
- Print the following pattern using python
- Python Program to Check Leap Year
- Remove first n characters from a string | Python
- Check if the first and last number of a list is the same | Python
- Number of occurrences of a substring in a string in Python
- Remove last element from list in Python
- How to Use Modulo Operator in Python
- Writing to a File using Python's print() Function
- How to read csv file in Python
- Dictionary Comprehension in Python
- How to Convert List to String in Python
- How to convert int to string in Python
- Random Float numbers in Python