Python enumerate

Python Enumerate #

enumerate() – built-in Python function that handles creating a counter for loop iterations.

The returned object is a tuple with a counter and a value.

It increments the count by 1 with each iteration.

Rather than this:

values = ["a", "b", "c"]
index = 0

for value in values:
    print(index, value)
    index += 1

# 0   a
# 1   b
# 2   c

Do this with enumerate():

for count, value in enumerate(values):
    print(count, value)

# 0   a
# 1   b
# 2   c

Note that enumerate() returns two loop variables: count and value. These can arbitrarily be named whatever in the for count, value part.

Starting value #

The starting value (i.e., index) can be changed to something other than 0.

for count, value in enumerate(values, start = 1):
    print(count, value)

# 1   a
# 2   b
# 3   c