Python Tuples : In this Unit…
Nested Tuples in Python can be best defined as a ‘tuple within another tuple’. A Python tuple can have elements of different type, when we take a tuple as an element of the main tuple, then that tuple is called a Nested tuple.
Consider two tuples, t1, t2
t1 = (1, 2, 3, 4)
t2 = (5, t1)
In the above code, we have added t1 as an element of tuple t2, hence, t1 is our nested tuple.
t1 = (1, 2, 3, 4)
t2 = (5, t1)
print(t2)
O/P
(5, (1, 2, 3, 4))
Hence,
t2[0] = 5
t2[1] = (1, 2, 3, 4)
So, t2[3] is our nested tuple. To print of the elements, we can use for loop, like
for i in t2[1]:
print(i, end= ' ')
O/P
1 2 3 4
Similarly,
t2[1][0] = 1
t2[1][1] = 2
t2[1][2] = 3
t2[1][3] = 4
Representing Tuples as Matrices
A matrix is a two-dimensional data structure where numbers are arranged into rows and columns.
For example, a matrix with two rows and two columns will look like

In Python, we can represent this matrix with Nested Tuple. For example, above matrix can be represented as
mat = ((2, 3), (1, 4))
Similarly, matrix for 3 by 3 will look like :
mat = ((1, 2, 3), (4, 5, 6), (7, 8, 9))
Here, (1, 2, 3) is the first row. Let’s try to access this matrix or Nested Tuples.
mat = ((2, 3), (1, 4))
for i in mat: # loop row by row
print(i)
O/P
(2, 3)
(1, 4)
Now, lets try to retrieve columns in each row
mat = ((2, 3), (1, 4))
for i in mat: # loop row by row
for j in i: # loop column
print(j, end = ' ')
print()
O/P
2 3
1 4
Another way of traversing nested tuple
mat = ((2, 3), (1, 4))
for i in range(len(mat)): # loop row by row
for j in range(len(mat[i])): # loop column
print(mat[i][j], end = ' ')
print()
O/P
2 3
1 4
That’s all here.
