Enumerate a Tuple in Python


Python - Enumerate a Tuple

In Python, enumerate() builtin function can take a tuple iterable as an argument and return an enumerated object created from the items in the tuple.

With the enumerated object in a For Loop, we can access the index of the items along with the items in the tuple.

Examples

1. Iterate over enumerated tuple

In this example, we take a tuple in myTuple variable, and iterate over the enumerated tuple, thus accessing both index (counter value) and item in the tuple in the loop.

Python Program

myTuple = ['mango', 58, 'India']

for index, item in enumerate(myTuple):
    print(index, ':', item)

Output

0 : mango
1 : 58
2 : India

2. Convert enumerated tuple object into a list of tuples

Using List Comprehension, we can convert the given tuple of items into a list of tuples, where each tuple contains the index and the respective item from the given tuple.

In this example, we will take a tuple in myTuple variable, and create a list of tuples from this tuple, where each tuple in the list contains the index and respective item from the original tuple.

Python Program

myTuple = ['mango', 58, 'India']

result = [x for x in enumerate(myTuple)]
print(result)

Output

[(0, 'mango'), (1, 58), (2, 'India')]

Summary

In this tutorial of Python Examples, we learned how to enumerate a tuple using enumerate() builtin function.