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

# Create a list that can be enumerated
L = ['red', 'green', 'blue']
x = list(enumerate(L))
print(x)
# Prints [(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.

# Start counter from 10
L = ['red', 'green', 'blue']
x = list(enumerate(L, 10))
print(x)
# Prints [(10, 'red'), (11, 'green'), (12, 'blue')]

Iterate Enumerate Object

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

L = ['red', 'green', 'blue']
for pair in enumerate(L):
    print(pair)
# Prints (0, 'red')
# Prints (1, 'green')
# Prints (2, 'blue')

You can unpack the tuple into multiple variables as well.

L = ['red', 'green', 'blue']
for index, item in enumerate(L):
    print(index, item)
# Prints 0 red
# Prints 1 green
# Prints 2 blue