Python enumerate() Function

Adds a counter to an iterable

Usage

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

By default, enumerate() starts counting at 0 but if you add a second argument start, it’ll start from that number instead.

Syntax

enumerate(iterable,start)

Python enumerate() function parameters
ParameterConditionDescription
iterableRequiredAn iterable (e.g. list, tuple, string etc.)
startOptionalA number to start counting from.
Default is 0.

Basic Example

Example: Create a list that can be enumerated

L = ['red', 'green', 'blue']
x = list(enumerate(L))
print(x)

Output:

[(0, 'red'), (1, 'green'), (2, 'blue')]

Specify Different Start

By default, enumerate() starts counting at 0 but if you add a second argument start, it’ll start from that number instead.

Example: Start enumerate() counter at 10

L = ['red', 'green', 'blue']
x = list(enumerate(L, 10))
print(x)

Output:

[(10, 'red'), (11, 'green'), (12, 'blue')]

Iterate Enumerate Object

When you iterate an enumerate object, you get a tuple containing (counter, item)

Example: Iterate enumerate object

L = ['red', 'green', 'blue']
for pair in enumerate(L):
    print(pair)

Output:

(0, 'red')
(1, 'green')
(2, 'blue')

You can unpack the tuple into multiple variables.

Example: Access index in for loop

L = ['red', 'green', 'blue']
for index, item in enumerate(L):
    print(index, item)

Output:

0 red
1 green
2 blue