Python program to sort the nested tuple using the sorted() function

By IncludeHelp Last updated : November 26, 2023

Problem statement

Given a tuple, write a Python program to sort the nested tuple using the sorted() function.

Let's learn about the sorted() function first.

Python sorted() function

The sorted() function is a built-in function in Python and it is used to get a sorted list of the specified iterable object. Below is the syntax,

sorted(iterable, key = key, reverse = reverse)

Sorting the nested tuple using the sorted() function

As per our requirement, to sort the nested tuple, use the sorted() function with the key and reverse parameters where required. Both these parameters are optional, you can use a key parameter to use a function to decide the order, and use the reverse parameter to decide the ascending or descending order.

Example

In this example, we have a nested tuple "students", we are sorting it based on different types of requirements.

# Python program to sort the nested tuple
# using the sorted() function
 
# Creating a nested tuple "students" with
# students id, name, and age
students = ((1, "Alex", 21), (3, "Bobby", 20), (2, "Chrestina", 19))
 
# Sorting the tuple by default
print(sorted(students))
 
# Sorting the tuple in reverse order
print(sorted(students, reverse=True))
 
# Sorting the tuple based on the name using lambda function
print(sorted(students, key=lambda value: value[1]))
 
# Sorting the tuple based on the name in reverse order using lambda function
print(sorted(students, key=lambda value: value[1], reverse=True))
 
# Sorting the tuple based on the word count using lambda function
print(sorted(students, key=lambda value: value[2]))
 
# Sorting the tuple on the word count in reverse using lambda function
print(sorted(students, key=lambda value: value[2], reverse=True))

Output

The output of the above program is:

[(1, 'Alex', 21), (2, 'Chrestina', 19), (3, 'Bobby', 20)]
[(3, 'Bobby', 20), (2, 'Chrestina', 19), (1, 'Alex', 21)]
[(1, 'Alex', 21), (3, 'Bobby', 20), (2, 'Chrestina', 19)]
[(2, 'Chrestina', 19), (3, 'Bobby', 20), (1, 'Alex', 21)]
[(2, 'Chrestina', 19), (3, 'Bobby', 20), (1, 'Alex', 21)]
[(1, 'Alex', 21), (3, 'Bobby', 20), (2, 'Chrestina', 19)]

Python Tuple Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.