Skip to main content

enumerate()

The enumerate() function in Python is a built-in function that allows you to loop over an iterable object while also keeping track of the index of the current item. It returns an enumerate object, which contains pairs of index and value for each item in the iterable. This can be helpful when you need both the index and value of items in a sequence during iteration.

Parameter Values

Parameter Description
iterable

An iterable object like a list, tuple, or string that you want to iterate over.

start

An optional parameter specifying the starting index value for the counter. Default is 0.

Return Values

The enumerate() function returns an iterator of tuples containing indices and items.

How to Use enumerate() in Python

Example 1:

The enumerate() function adds a counter to an iterable and returns it as an enumerate object.

for i, value in enumerate(['apple', 'banana', 'cherry']):
    print(i, value)
Example 2:

You can specify the start parameter to change the starting index of the counter.

for i, value in enumerate(['apple', 'banana', 'cherry'], start=1):
    print(i, value)
Example 3:

It can be useful when you need to track the index of items in a loop.

my_list = ['apple', 'banana', 'cherry']
for i, value in enumerate(my_list):
    print(f'Index {i}: {value}')