Sort a list of tuples in Python
Sorting data is a fundamental operation in programming, and Python provides powerful tools to accomplish this task efficiently. When dealing with lists of tuples, sorting becomes particularly useful, allowing us to organize data based on specific criteria within each tuples.
In this blog post, we will explore various methods to sort a list of tuples in Python. We will discuss the following topics:
- Sort list of tuples using sorted() function
- Sort a list of tuples by the first element
- Sort a list of tuples by the second element
- Sort a list of tuples in descending order
- Sort a list of tuples based on a custom sorting function
- Sort a list of tuples by multiple elements
- Sort list of tuples using itemgetter()
- Sort list of tuples by string values
- lambda function vs itemgetter()
- Sort list of tuples using sort() method
- Differences between sorted() function and sort() method
- Conclusion
Sort list of tuples using sorted() function
In Python, you can use the sorted()
function to sort any iterable object, such as lists, tuples, or strings.
The basic syntax of the sorted()
function is as follows:
sorted(iterable, key=None, reverse=False)
Parameters:
iterable
: This is the sequence that you want to sort, such as a list or tuple.key
: (Optional) A function that takes an element and returns a key for sorting. Useful for custom sorting.reverse
: (Optional) A boolean value. If True
, the elements are sorted in descending order. Default is False
.
(a) Sort a list of tuples by the first element
To sort a list of tuples by first element, you can use the sorted()
function along with a custom key function that extracts the first element of each tuple.
Here’s an example:
list_of_tuples = [(1, 20, 300), (100, 2, 30), (10, 200, 3)]
# Sort based on the first element (index 0) in each tuple
sorted_list = sorted(list_of_tuples, key=lambda x: x[0])
print(sorted_list) # Output: [(1, 20, 300), (10, 200, 3), (100, 2, 30)]
In this example, key=lambda x:x[0]
specifies that the sorting should be done based on the first element (index 0) of each tuple.
(b) Sort a list of tuples by the second element
To sort a list of tuples by the second element, you can use the sorted()
function along with a custom key function that extracts the second element of each tuple.
Here’s an example:
list_of_tuples = [(1, 20, 300), (100, 2, 30), (10, 200, 3)]
# Sort based on the second element (index 0) in each tuple
sorted_list = sorted(list_of_tuples, key=lambda x: x[1])
print(sorted_list) # Output: [(100, 2, 30), (1, 20, 300), (10, 200, 3)]
In this example, key=lambda x:x[1]
specifies that the sorting should be done based on the second element (index 1) of each tuple.
(c) Sort a list of tuples in descending order
To sort a list of tuples in descending order, you can set the reverse
parameter of the sorted()
function to True
.
Here’s an example that sorts a list of tuples based on the second element in descending order:
list_of_tuples = [(1, 20, 300), (100, 2, 30), (10, 200, 3)]
# Sort based on the second element (index 0) in each tuple in descending order
sorted_list = sorted(list_of_tuples, key=lambda x: x[1], reverse=True)
print(sorted_list) # Output: [(10, 200, 3), (1, 20, 300), (100, 2, 30)]
(d) Sort a list of tuples based on a custom sorting function
You can also define your own custom sorting function to decide the sorting criteria and pass it as the key
parameter to the sorted()
function.
Here’s an example that sorts a list of tuples based on the sum of their elements:
# Define a custom function to determine the sorting key
def my_func(subtuple):
# Returns the sum of elements in the subtuple
return sum(subtuple)
list_of_tuples = [(1, 20, 300), (100, 2, 30), (10, 200, 3)]
# Sorting based on the sum of elements in each tuple
sorted_list = sorted(list_of_tuples, key=my_func)
print(sorted_list) # Output: [(100, 2, 30), (10, 200, 3), (1, 20, 300)]
Here is another example that sorts a list of tuples based on the length of the first element:
# Define a custom function to determine the sorting key
def my_func(fruit_tuple):
# Returns the length of the first element in the tuple
return len(fruit_tuple[0])
# Example list of tuples representing fruits with names and prices
fruits = [("apple", 5), ("egg", 20), ("watermelon", 15)]
# Sorting the list of fruits based on the length of the first element
sorted_fruits = sorted(fruits, key=my_func)
print(sorted_fruits) # Output: [('egg', 20), ('apple', 5), ('watermelon', 15)]
(e) Sort a list of tuples by multiple elements
Sorting a list of tuples by multiple elements involves sorting based on multiple criteria or in a specific order for each tuple.
To sort a list of tuples by multiple elements, you can pass a tuple of key functions to the key
parameter of the sorted()
function.
Let’s consider an example where you have a list of tuples containing people with their names, ages, and salaries. You want to sort the list of tuples first by their age (ascending) and then by salary (descending). Here is the code:
# Example list of tuples representing people with names, ages, and salaries
people_data = [
("Alice", 25, 4000),
("Bob", 30, 5000),
("Charlie", 25, 8000),
("David", 30, 7000)
]
# Sorting the list of people by age (ascending) and then by salary (descending)
sorted_people = sorted(people_data, key=lambda person: (person[1], -person[2]))
print(sorted_people)
# Output: [('Charlie', 25, 8000), ('Alice', 25, 4000), ('David', 30, 7000), ('Bob', 30, 5000)]
In this example, the key parameter of the sorted()
function is set to a lambda function that returns a tuple (person[1], -person[2])
. This means the sorting is first done by age (index 1) in ascending order and then by salary (index 2) in descending order (the negative sign is used to achieve descending order).
(f) Sort list of tuples using itemgetter()
The itemgetter()
is a function from the operator
module in Python that allows you to access specific elements within a sequence (like a list or a tuple) based on their index.
You can use this function to sort a list of tuples. Here’s an example:
from operator import itemgetter
list_of_tuples = [(1, 20, 300), (100, 2, 30), (10, 200, 3)]
# Sort based on the second element (index 1) in each tuple
sorted_list = sorted(list_of_tuples, key=itemgetter(1))
print(sorted_list) # Output: [(100, 2, 30), (1, 20, 300), (10, 200, 3)]
In this example, itemgetter(1)
is used as the key function to sort the list of tuples based on the second element (index 1) in each tuple.
(g) Sort list of tuples by string values
Sorting a list of tuples based on string values requires special consideration, especially when dealing with case-insensitive sorting. Python provides built-in options to handle these scenarios.
Here’s an example:
# Example list of tuples representing fruits with names and prices
fruits = [("apple", 5), ("Banana", 20), ("Orange", 15), ("grape", 20)]
# Sorting the list of tuples of fruits alphabetically by name (case-insensitive)
sorted_fruits = sorted(fruits, key=lambda fruit: (fruit[0].casefold()))
print(sorted_fruits)
# Output: [('apple', 5), ('Banana', 20), ('grape', 20), ('Orange', 15)]
Using casefold()
ensures the fruit list is sorted alphabetically without considering case. This Python string method converts all Unicode characters to lowercase, making it more comprehensive than lower()
for case-insensitive comparisons.
(h) lambda function vs itemgetter()
Lambda function:
- They are ideal for complex sorting criteria involving comparisons, calculations, or conditional logic.
- They are generally slower than
itemgetter()
for large datasets due to the overhead of function calls
`itemgetter()`:
- If your sorting logic is straightforward,
itemgetter()
is often more readable and efficient. - It is faster than the lambda function due to its optimized implementations.
In summary, lambda functions are convenient if your sorting criteria are complex or if you are working with small datasets. However, for larger datasets or when performance is a concern, itemgetter()
is generally preferred due to its efficiency.
# Sort list of tuples using sort() method
Alternatively, you can also use the sort()
method to sort a list of tuples.
In Python, the sort()
method sorts the elements of the list in ascending order by default.
The basic syntax of the sort()
method is:
list_name.sort(key=None, reverse=False)
list_name
: The name of the list you want to sort.key
: (Optional) A function to execute to decide the order. Default is None
.reverse
: (Optional) A boolean. If True
the list is sorted in descending order. If False
(default), the list is sorted in ascending order.
Sort list of tuples by the first element
To sort a list of tuples by first element, you can use the sort()
method along with a custom key function that extracts the first element of each tuple.
Here is an example:
list_of_tuples = [(1, 20, 300), (100, 2, 30), (10, 200, 3)]
# Sort based on the second element (index 1) in each tuple
list_of_tuples.sort(key=lambda x: x[1])
print(list_of_tuples)
# Output: [(100, 2, 30), (1, 20, 300), (10, 200, 3)]
You can replace sorted()
function with the sort()
method for all the examples we talked about earlier in this guide.
Differences between sorted() function and sort() method
The sorted()
function and sort()
method are both used for sorting elements in a Python list, but they have some key differences:
(1) Return type:
sorted()
: Returns a new sorted list from the elements of the iterable (list, tuple, or string). The original iterable remains unchanged.sort()
: Sorts the elements of the list in-place and returnsNone
. The original list is modified.
(2) Mutability:
sorted()
: Creates a new sorted list without modifying the original iterable.sort()
: Modifies the original list in-place.
(3) Usage:
sorted()
: It can be used with any iterable (list, tuple, or string), not just lists. It returns a new sorted list regardless of the type of the original iterable.sort()
: Applies only to lists. It is a method of the list class and can only be used with lists.
(4) Performance:
The sort()
method is generally faster than the sorted()
function because it modifies the list in-place, avoiding the overhead of creating a new list.
Here’s a table summarizing the key differences:
Feature | sorted() | sort() |
Return Value | New sorted list | None |
Mutability | Non-mutating | Mutates original list |
Usage | Any iterable object | Lists only |
Performance | Generally slower | Generally faster |
Conclusion
In this guide, we discussed how to sort a list of tuples using the sorted()
and sort()
.
Here’s a summary of when to use each:
Use sorted()
:
- If you want to keep the original list intact.
- If you need to create a new sorted list from any iterable object.
Use sort()
:
- If you want to modify the original list and don’t need to keep the original order.
- If performance is a major concern.
Use lambda function:
- If your sorting criteria are complex or if you are working with small datasets.
Use itemgetter()
:
- For large datasets or when performance is a concern.
Happy → Coding →