Using the sorted() function or in-place sort are the ways to Sort a list of tuples by the first element in Python. Both methods need to use the key keyword.
Note: key
should be a function that identifies how to retrieve the comparable element from your data structure. In your case, it is the second element of the tuple, so we access [1]
.
Example Sort list of tuples by first element Python
Simple example code sort by the first element in the tuple.
Using sorted method
This method will not modify the original list of tuples.
a = [(2, 8), (0, 4), (1, 7)]
# sort by first element in tuple
res = sorted(a, key=lambda tup: tup[0])
print(res)
Output:
Do in-place sort
This method will change the original data.
a = [(2, 8), (0, 4), (1, 7)]
a.sort(key=lambda tup: tup[0])
print(a)
Output:
[(0, 4), (1, 7), (2, 8)]
Using the itemgetter()
function from the operator
module:
from operator import itemgetter
my_list = [(3, 'apple'), (1, 'banana'), (2, 'cherry')]
sorted_list = sorted(my_list, key=itemgetter(0))
print(sorted_list)
Using a list comprehension:
The list comprehension then creates a new list that contains only the second elements of the sorted tuples.
my_list = [(3, 'apple'), (1, 'banana'), (2, 'cherry')]
sorted_list = [tup for _, tup in sorted(my_list)]
print(sorted_list)
Comment if you have any doubts or suggestions on this Python tuple topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.