Python Nested Tuples

A tuple inserted inside another tuple is called nested tuple. For example,

tup = (50,60,70,80,90, (200, 201))

The tuple (200, 201) is called nested tuple as it is inside another tuple.

The nested tuple with the elements (200, 201) is treated as an element along with other elements in the tuple 'tup'. To retrieve the nested tuple, we can access it as an ordinary element as tup[5] as its index is 5.

Every nested tuple can represent a specific data record. For example, to store 4 employees data in 'emp' tuple, we can write:

emp = ((100, "Varun", 9000.90), (20, "Nihaarika", 5500.75), (30, "Vanaja",8900.00), (40, "Karthik", 5000.50))

Here, 'emp' is the tuple name. It contains 4 nested tuples each of which represents the data of an employee. Every employee's identification number, name and salary are stored as a nested tuples.

Sorting Nested Tuples

To sort a tuple, we can use sorted() function. This function sorts by default into ascending order. For example,
print(sorted(emp)) will sort the tuple 'emp' in ascending order of the 0th element in the nested tuples, i.e. identificaton number.
If we want to sort the tuple based on employee name, which is the 1st element in the nested tuples, we can use a lambda expression as: print(sorted(emp, key=lambda x: x[1]))
Here, key indicates the key for the sorted() function that tells on which element sorting should be done. The lambda function: lambda x: x[1] indicates that x[1] should be taken as the key that is nothing but 1st element. If we want to sort the tuple based on salary, we can use the lambda function as: lambda x: x[2].

print(sorted(emp)) #sorts by default on id

print(sorted(emp, reverse=True)) #reverses on id

print(sorted(emp, key=lambda x: x[1])) #sort on name

print(sorted(emp, key=lambda x: x[1],reverse=True))

print(sorted(emp, key=lambda x: x[2])) #sort on salary

print(sorted(emp, key=lambda x: x[2],reverse=True))