Nested Tuples

Tuples can contain other tuples as elements, which are known as nested tuples. Accessing elements in nested tuples requires additional indexing.

Creating Nested Tuples

Example 1: Tuple of Tuples

# Creating nested tuples
nested_tuple = (("Karthick AG", "Durai"), ("Vijay", "John"), ("Praveen", "Williams"))
print("Nested Tuple:", nested_tuple)

Output

Nested Tuple: (('Karthick AG', 'Durai'), ('Vijay', 'John'), ('Praveen', 'Williams'))

Accessing Elements in Nested Tuples

Example 2: Accessing Nested Elements

# Accessing elements in nested tuples
first_pair = nested_tuple[0]
first_name_in_first_pair = nested_tuple[0][0]
print("First Pair:", first_pair)
print("First Name in First Pair:", first_name_in_first_pair)

Output

First Pair: ('Karthick AG', 'Durai')

First Name in First Pair: Karthick AG

Looping Through Nested Tuples

Example 3: Iterating Over Nested Tuples

# Looping through nested tuples
for pair in nested_tuple:
    name1, name2 = pair
    print(f"Pair: {name1} and {name2}")

Output

Pair: Karthick AG and Durai

Pair: Vijay and John

Pair: Praveen and Williams

Explanation: By looping through the outer tuple and unpacking each inner tuple, we can access all the nested elements.