How To Sort Tuples In Python

Tuples are a widely used data structure in Python, and oftentimes we need to sort them for various reasons. Sorting tuples can be useful in various scenarios, such as sorting a list of student records by their grades, sorting a list of employees by their salaries, or sorting a list of coordinates by their distances from a specific point.

In all of these scenarios, sorting tuples makes it easier to analyze and process the data.

Methods of sorting tuples in Python

  • Using the sorted() function
  • Using the sort() method
  • Using the key parameter in the sorted() function.

Approach 1: Using the sorted() function

Using the sorted() function: The sorted() function returns a new sorted list from the elements of any iterable object. In the case of tuples, we can convert them into lists, sort them, and then convert them back to a tuple. Here’s an example:

Code:

tup = (4, 5, 1, 3, 2)
sorted_tup = tuple(sorted(tup))
print("Sorted Tuple", sorted_tup)

Output:

Sorted Tuple (1, 2, 3, 4, 5)

Explanation:

  1. The tuple ‘tup’ is defined with the elements (4, 5, 1, 3, 2).
  2. The sorted() function is called on the tuple ‘tup’, and the resulting sorted list is wrapped in the tuple() constructor to create a new tuple ‘sorted_tup’.
  3. The sorted tuple ‘sorted_tup’ is printed to the console using the print() function.

Approach 2: Using the sort() method

Using the sort() method: Unlike the sorted() function, which returns a new sorted list, the sort() method sorts the elements of a list in place. We can convert the tuple to a list, sort it using the sort() method, and then convert it back to a tuple. Here’s an example:

Code:

tup = (4, 5, 1, 3, 2)
list_tup = list(tup)
list_tup.sort()
sorted_tup = tuple(list_tup)
print("Sorted Tuple", sorted_tup)

Output:

Sorted Tuple (1, 2, 3, 4, 5)

Explanation:

  1. The tuple ‘tup’ is defined with the elements (4, 5, 1, 3, 2).
  2. The tuple is first converted into a list ‘list_tup’ using the list() constructor.
  3. The sort() method is called on the list ‘list_tup’, which sorts the elements of the list in ascending order.
  4. The sorted list is converted back to a tuple ‘sorted_tup’ using the tuple() constructor.
  5. The sorted tuple ‘sorted_tup’ is printed to the console using the print() function.

Approach 3: Using key parameter in the sorted() function

Using the key parameter in the sorted() function: We can sort tuples based on a specific element within each tuple by specifying the key parameter in the sorted() function. Here’s an example:

Code:

tup = [('John', 25), ('Bob', 20), ('Alice', 30)]
sorted_tup = sorted(tup, key=lambda x: x[1])
print("Sorted Tuple", sorted_tup)

Output:

Sorted Tuple [('Bob', 20), ('John', 25), ('Alice', 30)]

Explanation:

  1. The list of tuples ‘tup’ is defined with the elements [(‘John’, 25), (‘Bob’, 20), (‘Alice’, 30)].
  2. The sorted() function is called on the list of tuples ‘tup’, and the key parameter is used to specify the sorting key, which is the second element (age) of each tuple.
  3. The lambda function passed as the key parameter tells Python to use the second element of each tuple as the sorting key.
  4. The resulting sorted list of tuples is stored in the variable ‘sorted_tup’.
  5. The sorted tuple ‘sorted_tup’ is printed to the console using the print() function.

Best approach on How To Sort Tuples In Python

The best approach for sorting tuples in Python is the built-in sorted() function with a lambda function key is often considered the best approach because it is efficient and flexible. It allows sorting by single or multiple elements, ascending or descending order, and can handle complex data types such as nested tuples or objects. It also has a built-in sorting algorithm that is optimized for speed and memory usage.

Some key qualities of the sorted() function approach for sorting tuples in Python include

  • Flexibility: The sorted() function can be used with different data types and sorting criteria, allowing for customization and adaptability to different use cases.
  • Efficiency: The built-in sorting algorithm of the sorted() function is optimized for performance, making it an efficient way to sort large lists of tuples.
  • Readability: The use of lambda functions with the sorted() function allows for concise and readable code, making it easy to understand and maintain.

Sample problems on How To Sort Tuples In Python:

1. Given a list of tuples containing a name and a score, sort the list in descending order based on the score.

Code:

tup = [('John', 80), ('Bob', 70), ('Alice', 90)]
sorted_tup = sorted(tup, key=lambda x: x[1], reverse=True)
print("Sorted Tuple", sorted_tup)

Output:

Sorted Tuple [('Alice', 90), ('John', 80), ('Bob', 70)]

Explanation:

  1. The list of tuples ‘tup’ is defined with the elements [(‘John’, 80), (‘Bob’, 70), (‘Alice’, 90)].
  2. The sorted() function is called on the list of tuples ‘tup’, and the key parameter is used to specify the sorting key, which is the second element (score) of each tuple.
  3. The lambda function passed as the key parameter tells Python to use the second element of each tuple as the sorting key.
  4. The reverse parameter is set to True to sort the list in descending order.
  5. The resulting sorted list of tuples is stored in the variable ‘sorted_tup’.
  6. The sorted tuple ‘sorted_tup’ is printed to the console using the print() function.

2. Given a list of tuples representing the name, age, and weight of a group of people, write a Python program to sort the list in ascending order by age, and then by weight for people with the same age.

Code:

tup = [('John', 25, 70), ('Bob', 20, 75), ('Alice', 30, 65), ('Sam', 25, 80)]
sorted_tup = sorted(tup, key=lambda x: (x[1], x[2]))
print("Sorted Tuple", sorted_tup)

Output:

Sorted Tuple [('Bob', 20, 75), ('John', 25, 70), ('Sam', 25, 80), ('Alice', 30, 65)

Explanation:

  1. This solution defines a list of tuples ‘tup’ with the elements [(‘John’, 25, 70), (‘Bob’, 20, 75), (‘Alice’, 30, 65), (‘Sam’, 25, 80)], representing the name, age, and weight of four people.
  2. The sorted() function is then called on the list of tuples ‘tup’, with the key parameter set to a lambda function that returns a tuple of the second and third elements (age and weight) of each tuple.
  3. The resulting sorted list of tuples is stored in the variable ‘sorted_tup’, and then printed to the console using the print() function.

Conclusion

Sorting tuples in Python is a common operation that can be performed using various methods. We discussed three methods of sorting tuples in Python and their advantages and disadvantages. The best approach for sorting tuples depends on the specific requirements of your application.