Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to sort a list of tuples alphabetically
When it is required to sort a list of tuples in alphabetical order, the sort() method can be used. This method performs in-place sorting, meaning the original list gets modified.
The sort() function sorts values in ascending order by default. If descending order is needed, you can specify reverse=True.
A list of tuples contains multiple tuples enclosed within a list. We can sort these tuples based on any element within each tuple using a key function.
Sorting by First Element
Here's how to sort a list of tuples alphabetically by the first element ?
def sort_tuple_vals(my_list):
my_list.sort(key=lambda x: x[0])
return my_list
my_list = [("Hey", 18), ("Jane", 33), ("Will", 56), ("Nysa", 35), ("May", "Pink")]
print("The original list is:")
print(my_list)
print("After sorting alphabetically by first element:")
print(sort_tuple_vals(my_list))
The original list is:
[('Hey', 18), ('Jane', 33), ('Will', 56), ('Nysa', 35), ('May', 'Pink')]
After sorting alphabetically by first element:
[('Hey', 18), ('Jane', 33), ('May', 'Pink'), ('Nysa', 35), ('Will', 56)]
Using sorted() for Non-destructive Sorting
To keep the original list unchanged, use sorted() instead ?
original_list = [("Hey", 18), ("Jane", 33), ("Will", 56), ("Nysa", 35)]
sorted_list = sorted(original_list, key=lambda x: x[0])
print("Original list:", original_list)
print("Sorted list:", sorted_list)
Original list: [('Hey', 18), ('Jane', 33), ('Will', 56), ('Nysa', 35)]
Sorted list: [('Hey', 18), ('Jane', 33), ('Nysa', 35), ('Will', 56)]
Sorting by Different Elements
You can sort by any element within the tuples ?
data = [("Alice", 25), ("Bob", 20), ("Charlie", 30)]
# Sort by second element (age)
by_age = sorted(data, key=lambda x: x[1])
print("Sorted by age:", by_age)
# Sort by first element in reverse order
by_name_desc = sorted(data, key=lambda x: x[0], reverse=True)
print("Sorted by name (descending):", by_name_desc)
Sorted by age: [('Bob', 20), ('Alice', 25), ('Charlie', 30)]
Sorted by name (descending): [('Charlie', 30), ('Bob', 20), ('Alice', 25)]
Comparison
| Method | Modifies Original? | Returns | Best For |
|---|---|---|---|
list.sort() |
Yes | None | In-place sorting |
sorted() |
No | New sorted list | Preserving original |
Conclusion
Use list.sort(key=lambda x: x[0]) for in-place alphabetical sorting of tuples. Use sorted() when you need to preserve the original list unchanged.
