In this python tuple program, we will sort a list of tuples by the length of the tuple.
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 length of the tuple i.e. len() function to the key inside the sorted().
- Print the output.
l = [(4, 5, 6), ( 6, ), ( 2, 3), (6, 7, 8, 9, 0 ) ]
print("Original list of tuples: ",l)
res = sorted(l, key=lambda tup: len(tup))
print("After sorting list of tuples by length of tuples: ",res)
Output :
Original list of tuples: [(4, 5, 6), (6,), (2, 3), (6, 7, 8, 9, 0)]
After sorting list of tuples by length of tuples: [(6,), (2, 3), (4, 5, 6), (6, 7, 8, 9, 0)]