Last modified: Aug 12, 2026
Sort Tuples by First and Second Element
Sorting data is a common task in Python. When you work with lists of tuples, you often need to sort them. The order can be based on the first element, the second element, or both. This guide explains how to do it clearly and efficiently.
You will learn several methods. We will use the built-in sorted() function and the list.sort() method. We will also explore the powerful itemgetter() function from the operator module. By the end, you will sort tuples like a pro.
Understanding Tuples and Sorting
A tuple is an ordered, immutable collection. It can hold multiple items. For example, (3, 'apple') is a tuple. A list of tuples looks like [(3, 'apple'), (1, 'banana')].
By default, Python sorts tuples element by element. It compares the first items. If they are equal, it compares the second items, and so on. This is called lexicographical order. It is often what you need.
However, sometimes you want to control the sorting key. You might want to sort only by the second element. Or you might want to reverse the order. The techniques below give you that control.
Method 1: Using sorted() with Default Behavior
The simplest way is to use the sorted() function. It returns a new sorted list. By default, it sorts by the first element, then the second.
# List of tuples
data = [(3, 'pear'), (1, 'apple'), (2, 'banana'), (1, 'cherry')]
# Sort by first element, then second
sorted_data = sorted(data)
print(sorted_data)
[(1, 'apple'), (1, 'cherry'), (2, 'banana'), (3, 'pear')]
Notice that for the tuples with 1, it sorted by the second element. 'apple' comes before 'cherry'. This is the default behavior. It is perfect for many cases.
If you want to sort in descending order, use the reverse=True parameter.
# Sort in descending order
sorted_data_desc = sorted(data, reverse=True)
print(sorted_data_desc)
[(3, 'pear'), (2, 'banana'), (1, 'cherry'), (1, 'apple')]
This method is clean and requires no extra imports. It is great for beginners. For more complex sorting, keep reading.
Method 2: Using key with lambda
Sometimes you want to sort only by the second element. The key parameter lets you specify a function. This function returns the value to sort by. A lambda function is perfect for this.
# List of tuples
data = [(3, 'pear'), (1, 'apple'), (2, 'banana')]
# Sort by second element (the string)
sorted_by_second = sorted(data, key=lambda x: x[1])
print(sorted_by_second)
[(1, 'apple'), (2, 'banana'), (3, 'pear')]
Here, lambda x: x[1] tells Python to use the second element of each tuple as the sorting key. This is very flexible. You can sort by any index you want.
You can also sort by multiple keys using a tuple in the lambda. For example, to sort by the second element first, then the first element, you would write:
# Sort by second element, then by first element
sorted_multi = sorted(data, key=lambda x: (x[1], x[0]))
print(sorted_multi)
[(1, 'apple'), (2, 'banana'), (3, 'pear')]
This gives you full control. It is a bit more verbose, but very clear. Many developers prefer this for simple cases.
Method 3: Using itemgetter() for Speed and Clarity
For better performance and cleaner code, use itemgetter() from the operator module. This function is optimized for this exact purpose. It is often faster than a lambda.
First, import it. Then, pass the indices you want to sort by.
from operator import itemgetter
# List of tuples
data = [(3, 'pear'), (1, 'apple'), (2, 'banana'), (1, 'cherry')]
# Sort by first element
sorted_by_first = sorted(data, key=itemgetter(0))
print(sorted_by_first)
# Sort by second element
sorted_by_second = sorted(data, key=itemgetter(1))
print(sorted_by_second)
# Sort by first, then second
sorted_both = sorted(data, key=itemgetter(0, 1))
print(sorted_both)
[(1, 'apple'), (1, 'cherry'), (2, 'banana'), (3, 'pear')]
[(1, 'apple'), (2, 'banana'), (1, 'cherry'), (3, 'pear')]
[(1, 'apple'), (1, 'cherry'), (2, 'banana'), (3, 'pear')]
Look at the second output. It sorted by the string values. 'apple', 'banana', 'cherry', 'pear' are in alphabetical order. This is very readable.
The itemgetter(0, 1) call sorts by the first element, then the second. This is the same as the default behavior, but it is more explicit. It is also faster when sorting large lists.
This method is highly recommended for production code. It is both fast and clear.
Sorting in Place with list.sort()
If you don't need the original list, you can modify it directly. The list.sort() method sorts the list in place. It returns None. This is more memory-efficient for large lists.
# List of tuples
data = [(3, 'pear'), (1, 'apple'), (2, 'banana')]
# Sort in place by first element
data.sort(key=itemgetter(0))
print(data)
[(1, 'apple'), (2, 'banana'), (3, 'pear')]
You can use all the same key functions with list.sort(). This includes lambdas and itemgetter(). Just remember that it changes the original list.
This is useful when you want to save memory. It is also common in data processing pipelines.
Reversing the Sort Order
You can easily reverse the order of sorting. Use the reverse=True parameter with sorted() or list.sort(). This works with all the methods above.
from operator import itemgetter
data = [(3, 'pear'), (1, 'apple'), (2, 'banana')]
# Sort by second element, descending
sorted_desc = sorted(data, key=itemgetter(1), reverse=True)
print(sorted_desc)
[(3, 'pear'), (2, 'banana'), (1, 'apple')]
This gives you complete control over the order. It is simple and effective.
Practical Example: Sorting Student Records
Let's put it all together. Imagine you have a list of student records. Each record is a tuple with name, grade, and age.
from operator import itemgetter
students = [
('Alice', 85, 20),
('Bob', 90, 22),
('Charlie', 85, 19),
('David', 90, 21)
]
# Sort by grade (descending), then by age (ascending)
sorted_students = sorted(students, key=itemgetter(1, 2), reverse=True)
print("Sorted by grade (desc), then age (asc):")
for student in sorted_students:
print(student)
Sorted by grade (desc), then age (asc):
('Bob', 90, 22)
('David', 90, 21)
('Alice', 85, 20)
('Charlie', 85, 19)
Wait, the output is not exactly what we wanted. We wanted grade descending, but age ascending. With reverse=True, it reverses both. To fix this, we need a different approach.
We can sort by grade descending and age ascending by using a lambda with negative values. Or we can sort in two steps. Let's do it in two steps for clarity.
# Step 1: Sort by age ascending
students.sort(key=itemgetter(2))
# Step 2: Sort by grade descending (stable sort)
students.sort(key=itemgetter(1), reverse=True)
print("Sorted by grade (desc), then age (asc):")
for student in students:
print(student)
Sorted by grade (desc), then age (asc):
('Bob', 90, 22)
('David', 90, 21)
('Charlie', 85, 19)
('Alice', 85, 20)
Now it is correct. Python's sort is stable. This means it preserves the order of equal elements. By sorting by age first, then by grade, we get the desired result. This is a powerful technique.
Remember, for a single sort with mixed orders, use a lambda with negative numbers. For example, key=lambda x: (-x[1], x[2]) for grade descending and age ascending.
Performance Considerations
When sorting large lists, performance matters. The itemgetter() function is generally faster than a lambda. This is because it is implemented in C. For lists with thousands of tuples, the difference can be noticeable.
However, for most use cases, the lambda is perfectly fine. The readability and simplicity often outweigh the tiny performance gain. Choose the method that makes your code clear.
Always test with your actual data size. Premature optimization is not recommended. Write clean code first, then optimize if needed.
Common Pitfalls and Tips
One common mistake is forgetting that tuples are zero-indexed. The first element is index 0, not 1. Always double-check your indices.
Another pitfall is mixing types. If you have tuples with integers and strings, sorting might raise a TypeError. Make sure your tuples have comparable types.
If you are working with lists of tuples and need to remove items, you might find our guide on Python List Remove by Index useful. It shows how to handle list modifications.
Also, if you have missing data, you might need to handle it before sorting. Check out our article on Remove NaN from Python List to clean your data first.
For more list operations, you can learn about Python List Append to End. This is a fundamental skill.
Conclusion
Sorting a list of tuples by first and second element is easy in Python. You have several powerful tools at your disposal. Use sorted() for a new list. Use list.sort() to modify in place.
For simple sorting, the default behavior works well. For more control, use a lambda function. For speed and clarity, use itemgetter() from the operator module.
Remember to use the key parameter to specify the sorting criteria. Use reverse=True to change the order. And remember that Python's sort is stable, which allows for multi-pass sorting.
With these techniques, you can handle any tuple sorting task. Practice with your own data to become more comfortable. Happy coding!