How to Sort List of Tuples by Second Element in Python
To sort a list of tuples by the second element in Python, use the
sorted() function or the list's sort() method with a key argument like key=lambda x: x[1]. This tells Python to sort the tuples based on their second item.Syntax
Use the sorted() function or the list's sort() method with a key parameter. The key is a function that tells Python which element to use for sorting.
sorted(list_of_tuples, key=lambda x: x[1]): Returns a new sorted list.list_of_tuples.sort(key=lambda x: x[1]): Sorts the list in place.
python
sorted_list = sorted(list_of_tuples, key=lambda x: x[1]) list_of_tuples.sort(key=lambda x: x[1])
Example
This example shows how to sort a list of tuples by their second element using both sorted() and list.sort(). The output shows the list sorted by the second value in each tuple.
python
list_of_tuples = [(1, 3), (4, 1), (2, 2), (5, 0)] # Using sorted() to get a new sorted list sorted_list = sorted(list_of_tuples, key=lambda x: x[1]) print("Sorted with sorted():", sorted_list) # Using list.sort() to sort in place list_of_tuples.sort(key=lambda x: x[1]) print("Sorted with list.sort():", list_of_tuples)
Output
Sorted with sorted(): [(5, 0), (4, 1), (2, 2), (1, 3)]
Sorted with list.sort(): [(5, 0), (4, 1), (2, 2), (1, 3)]
Common Pitfalls
One common mistake is forgetting to use the key parameter, which causes Python to sort by the first element of the tuple by default. Another is trying to sort by an index that does not exist, which raises an error.
Also, using sorted() returns a new list and does not change the original list, while list.sort() changes the list itself.
python
list_of_tuples = [(1, 3), (4, 1), (2, 2)] # Wrong: missing key, sorts by first element wrong_sort = sorted(list_of_tuples) print("Wrong sort (by first element):", wrong_sort) # Correct: sort by second element correct_sort = sorted(list_of_tuples, key=lambda x: x[1]) print("Correct sort (by second element):", correct_sort)
Output
Wrong sort (by first element): [(1, 3), (2, 2), (4, 1)]
Correct sort (by second element): [(4, 1), (2, 2), (1, 3)]
Quick Reference
- sorted(list, key=lambda x: x[1]): Returns a new list sorted by second element.
- list.sort(key=lambda x: x[1]): Sorts the list in place by second element.
- Use
lambda x: x[1]to pick the second element for sorting. - Remember index starts at 0, so second element is index 1.
Key Takeaways
Use the key parameter with a lambda function to sort by the second element.
sorted() returns a new sorted list; list.sort() changes the list itself.
The second element in a tuple is accessed with index 1.
Without key, sorting defaults to the first element of the tuple.
Always check tuple length to avoid index errors when sorting.