w3resource

Python: Sort a list of lists by length and value using lambda

Python Lambda: Exercise-28 with Solution

Write a Python program to sort a given list of lists by length and value using lambda.

Sample Solution:

Python Code :

 # Define a function 'sort_sublists' that takes a list of lists 'input_list' as input
def sort_sublists(input_list):
    # Sort the 'input_list' based on two criteria:
    # 1. First, sort by the length of each sublist (ascending order)
    # 2. If the lengths are equal, sort lexicographically by the sublist elements themselves
    result = sorted(input_list, key=lambda l: (len(l), l))
    
    # Return the sorted list of lists
    return result

# Create a list of lists named 'list1'
list1 = [[2], [0], [1, 3], [0, 7], [9, 11], [13, 15, 17]]

# Print the original list 'list1'
print("Original list:")
print(list1)

# Sort the list of lists by length and value using the 'sort_sublists' function and print the result
print("\nSort the list of lists by length and value:")
print(sort_sublists(list1))

Sample Output:

Original list:
[[2], [0], [1, 3], [0, 7], [9, 11], [13, 15, 17]]

Sort the list of lists by length and value:
[[0], [2], [0, 7], [1, 3], [9, 11], [13, 15, 17]]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to sort each sublist of strings in a given list of lists using lambda.
Next: Write a Python program to find the maximum value in a given heterogeneous list using lambda.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.