How to Sort List of Tuples in Python: Simple Guide
To sort a list of tuples in Python, use the
sorted() function or the list's .sort() method. You can sort by the first element by default or specify a different element using the key parameter with a lambda function.Syntax
The basic syntax to sort a list of tuples is:
sorted(list_of_tuples)- returns a new sorted list by the first tuple element.list_of_tuples.sort()- sorts the list in place by the first tuple element.sorted(list_of_tuples, key=lambda x: x[index])- sorts by the tuple element atindex.list_of_tuples.sort(key=lambda x: x[index])- sorts in place by the tuple element atindex.
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 the second element in each tuple.
python
data = [(3, 'apple'), (1, 'banana'), (2, 'cherry')] sorted_data = sorted(data, key=lambda x: x[1]) print(sorted_data)
Output
[(3, 'apple'), (1, 'banana'), (2, 'cherry')]
Common Pitfalls
Common mistakes include:
- Not using
keywhen you want to sort by an element other than the first. - Confusing
sorted()(which returns a new list) with.sort()(which changes the list itself). - Using an invalid index in the lambda function causing errors.
python
data = [(3, 'apple'), (1, 'banana'), (2, 'cherry')] # Wrong: sorts by first element, not second wrong_sorted = sorted(data) # Right: sorts by second element right_sorted = sorted(data, key=lambda x: x[1]) print('Wrong:', wrong_sorted) print('Right:', right_sorted)
Output
Wrong: [(1, 'banana'), (2, 'cherry'), (3, 'apple')]
Right: [(3, 'apple'), (1, 'banana'), (2, 'cherry')]
Quick Reference
Summary tips for sorting lists of tuples:
- Use
sorted()to get a new sorted list without changing the original. - Use
.sort()to sort the list in place. - Use the
keyparameter with a lambda to sort by any tuple element. - Remember tuple indexes start at 0.
Key Takeaways
Use
sorted() or .sort() to sort lists of tuples in Python.By default, sorting uses the first tuple element; use
key=lambda x: x[index] to sort by other elements.sorted() returns a new list; .sort() changes the original list.Always check tuple indexes start at zero to avoid errors.
Sorting tuples is useful for organizing data by any tuple field.