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
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) print(res)
Do in-place sort
This method will change the original data.
a = [(2, 8), (0, 4), (1, 7)] a.sort(key=lambda tup: tup) print(a)
[(0, 4), (1, 7), (2, 8)]
Do comment if you have any doubts and suggestions on this Python tuple topic.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.