In this python tuple program, we will sort a list of tuples by the second item.
Steps to solve the program
- Take a list of tuples as input.
- Use sorted() to sort the tuple and pass the lambda function to sort the tuple by the second item to the key inside the sorted().
- Print the output.
l = [(1,5),(7,8),(4,0),(3,6)]
print("Original list of tuples: ",l)
res = sorted(l, key=lambda tup: tup[1])
print("After sorting list of tuples by second element: ",res)
Output :
Original list of tuples: [(1, 5), (7, 8), (4, 0), (3, 6)]
After sorting list of tuples by second element: [(4, 0), (1, 5), (3, 6), (7, 8)]