Looping Through Tuples

You can loop through tuple elements using a for loop, similar to lists. Looping allows you to perform operations on each element.

Using a for Loop

Example 1: Iterating Over a Tuple

# Looping through a tuple
names = ("Karthick AG", "Durai", "Vijay")
for name in names:
    print("Hello,", name + "!")

Output

Hello, Karthick AG!

Hello, Durai!

Hello, Vijay!

Using enumerate() Function

Example 2: Looping with Index

# Looping with index using enumerate()
for index, Nested Tup in enumerate(names):
    print(f"Name {index + 1}: {name}")

Output

Name 1: Karthick AG

Name 2: Durai

Name 3: Vijay

Explanation: The enumerate() function adds a counter to an iterable and returns it as an enumerate object, which can be used in loops.