Python tuple program to sort a list of tuples by the second item

In this python tuple program, we will sort a list of tuples by the second item.

Steps to solve the program
  1. Take a list of tuples as input.
  2. 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().
  3. 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)]
				
			

sort a list of tuples by the first item.

sort a list of tuples by the length of the tuple.

Leave a Comment