The enumerate() function in Python

The enumerate() function takes two arguments: an iterable, and an optional argument start, and returns an enumerate object with an index attached to each item of the iterable.

The start argument sets the number to start the count.

Code Example

If you print the return of the function you will just see the object reference, to actually see the items you have to convert it to a list or tuple.

>>> car_brands = ['ferrari', 'bmw', 'mclaren']
>>> enum_brands = enumerate(car_brands)
>>> 
>>> print(enum_brands)
<enumerate object at 0x7f96047c5880>
>>> 
>>> list(enum_brands)
[(0, 'ferrari'), (1, 'bmw'), (2, 'mclaren')]

Setting a different starting index:

>>> car_brands = ['ferrari', 'bmw', 'mclaren']
>>> enum_brands = enumerate(car_brands, 5)
>>> list(enum_brands)
[(5, 'ferrari'), (6, 'bmw'), (7, 'mclaren')]

The enumerate() shows its usefulness when used combined with a for loop.

>>> car_brands = ['ferrari', 'bmw', 'mclaren']
>>> for key, value in enumerate(car_brands):
...     print(f'{key}: {value}')
... 
0: ferrari
1: bmw
2: mclaren

When you loop through an iterable, such as a list, there is a chance you also want a key or an index for each item, and the enumerate() function gives you this index easily.