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)
  1. iterable - a sequence or objects that support iteration.
  2. start - (optional) start counting from this value .
The enumerated object can then be used directly for loops or converted into a list of tuples using the list() method. You can specify the starting index for the counting by providing a second argument to the enumerate function, like this:
for index, value in enumerate(iterable, start=1): # do something with index and value
  1. iterable - a sequence or objects that support iteration.
  2. 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:


Python Enumerate
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.