In the previous chapter, we looked at the introduction of Tuples, the creation of tuples in several ways, and the functions that we can use on tuples to perform a wide range of operations. In this chapter, we will discuss the concept of Nested Tuples in Python.
Link to all chapters of Python here: Learn Python
Nested Tuples in Python
Just as the name sounds, a nested tuple means a tuple inside another tuple. Find an example here below.
nested_tuple = (11,22,33,(33,77))
print(nested_tuple[3])
Output
(33, 77)
In the example shared above, you can notice that the declared nested_tuple has another tuple (33,77) at index location 3.
This concept can be helpful when you want to store the data of a group of students or employees. You can also use the sorted() function to sort the elements in a tuple. By default, the sorted() function arranges elements in ascending order. It would help if you used reverse=True within the sorted() function to set elements in descending order. Let us look at a program to understand the same.
#create a tuple with student details
students = ((11,"Warner",97),(12,"Samson",150),(7,"Dhoni",77))
print("Students in declared order: \n{}".format(students))
print("Students in ascending order: \n{}".format(sorted(students)))
print("Students in descending order: \n{}".format(sorted(students,reverse=True)))
print("Students sorted as per name: \n{}".format(sorted(students, key=lambda n:n[1])))
print("Students sorted as per marks: \n{}".format(sorted(students, key=lambda n:n[2])))
Output
Students in declared order:
((11, 'Warner', 97), (12, 'Samson', 150), (7, 'Dhoni', 77))
Students in ascending order:
[(7, 'Dhoni', 77), (11, 'Warner', 97), (12, 'Samson', 150)]
Students in descending order:
[(12, 'Samson', 150), (11, 'Warner', 97), (7, 'Dhoni', 77)]
Students sorted as per name:
[(7, 'Dhoni', 77), (12, 'Samson', 150), (11, 'Warner', 97)]
Students sorted as per marks:
[(7, 'Dhoni', 77), (11, 'Warner', 97), (12, 'Samson', 150)]