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

In this python tuple program, we will sort a list of tuples by the first 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 first 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[0])
print("After sorting list of tuples by first element: ",res)
				
			

Output :

				
					Original list of tuples:  [(1, 5), (7, 8), (4, 0), (3, 6)]
After sorting list of tuples by first element:  [(1, 5), (3, 6), (4, 0), (7, 8)]
				
			

remove Tuples from the List having every element as None.

sort a list of tuples by the second item.

Leave a Comment