# Sort a list of tuples by the first or second element in Python

In Python, sorted() sorts a list of tuples by the first element.

s = [('b', 1), ('a', 3), ('c', 2)]

s1 = sorted(s)
s2 = sorted(s, reverse=True)
s3 = sorted(s, reverse=False)

print(s1)  # [('a', 3), ('b', 1), ('c', 2)]
print(s2)  # [('c', 2), ('b', 1), ('a', 3)]
print(s3)  # [('a', 3), ('b', 1), ('c', 2)]


sorted() returns a sorted list. That reverse option is True sorts a list by descending.

## Sort a list of tuples by the second element

from operator import itemgetter

s = [('b', 1), ('a', 3), ('c', 2)]

s1 = sorted(s, key=itemgetter(1))
s2 = sorted(s, key=itemgetter(1), reverse=True)
s3 = sorted(s, key=itemgetter(1), reverse=False)

print(s1)  # [('b', 1), ('c', 2), ('a', 3)]
print(s2)  # [('a', 3), ('c', 2), ('b', 1)]
print(s3)  # [('b', 1), ('c', 2), ('a', 3)]


To sort a list of tuples by the second element, use itemgetter from operator.

## sort()

s4 = [('b', 1), ('a', 3), ('c', 2)]
s5 = [('b', 1), ('a', 3), ('c', 2)]

s4.sort(reverse=True)
s5.sort(reverse=False)

print(s4)  # [('c', 2), ('b', 1), ('a', 3)]
print(s5)  # [('a', 3), ('b', 1), ('c', 2)]


sort() also sorts a list.