Python tuple - How to iterate the tuple and get the index in the for statement

You can iterate a tuple in the for statement in Python.

t = (1, 2, 3, 4)

for i in t:

# 1
# 2
# 3
# 4

Each element of the tuple is printed.

Get the index and element of a tuple

Do you want to get the index while iterating? Let's use the built-in function enumerate().

t = ('A', 'B', 'C')

for i in enumerate(t):

# (0, 'A')
# (1, 'B')
# (2, 'C')

You can iterate what the enumerate() returns and get the indexes and values of a tuple as pairs. The enumerate() returns the pairs of index and value. You can get access to each index and value like that.

t = ('A', 'B', 'C')

for index, value in enumerate(t):
    print(f'{index} ... {value}')

# 0 ... A
# 1 ... B
# 2 ... C

Above way is the same as iterating a Python dictionary.

Python Tuple

Python Tutorial