Sort list of tuples by first element Python | Example code

Using 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:

Sort list of tuples by first element Python

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)]

Do comment if you have any doubts and suggestions on this Python tuple topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.