In this Python Tuples article we want to learn How to Create Nested Tuples in Python, Tuples are a fundamental data structure in Python, used to store and organize data. tuple is a sequence of values that are immutable and it means that they cannot be changed after the tuple is created. Nested tuples are simply tuples that contain other tuples as elements. in this article we want to talk how to create nested tuples.
How to Create Nested Tuples in Python
For creating nested tuple you can simply include one or more tuples as elements within a tuple, in the below example we have first created simple tuple t1 containing three integers. after that we have created nested tuple t2 that includes t1 as one of its elements. and lastly we create another nested tuple t3 that includes t2 as one of its elements.
1 2 3 4 5 6 7 8 9 10 |
#simple tuple containing three integers t1 = (1, 2, 3) #nested tuple containing t1 as an element t2 = (4, 5, t1) #nested tuple containing t2 as an element t3 = ('a', 'b', t2) print(t3) |
This will be the result
For accessing the elements of a nested tuple you can use indexing, just as you would with regular tuple.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#simple tuple containing three integers t1 = (1, 2, 3) #nested tuple containing t1 as an element t2 = (4, 5, t1) #nested tuple containing t2 as an element t3 = ('a', 'b', t2) print(t3[0]) print(t3[2]) print(t3[2][2]) print(t3[2][2][1]) |
This will be the result
You can also iterate over nested tuple using for loop, just as you would with regular tuple.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#simple tuple containing three integers t1 = (1, 2, 3) #nested tuple containing t1 as an element t2 = (4, 5, t1) #nested tuple containing t2 as an element t3 = ('a', 'b', t2) # Iterating over nested tuple for i in t3: if isinstance(i, tuple): for j in i: print(j) else: print(i) |
This will be the result