set of tuples sort by first element python code example
Example 1: sort tuple by first element python
a = [(5,8), (3,4), (9,7)]
result = sorted(a, key=lambda tup: tup[0])
a.sorted(key = lambda tup: tup[0])
[(3, 4), (5, 8), (9, 7)]
Example 2: how to sort a list by the second element in tuple python
def sort_prices(list_of_tuples):
list_of_tuples.sort(key=lambda x: x[1], reverse=True)
return list_of_tuples, print(list_of_tuples)
Example 3: how to sort tuples in python
a = (3,1,2)
a = list(a)
a.sort()
print(a)
>>> [1,2,3]
a = [3, 6, 8, 2, 78, 1, 23, 45, 9]
print(sorted(a))
>>> [1, 2, 3, 6, 8, 9, 23, 45, 78]