w3resource

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


28. Sort Lists by Length & Value Lambda

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]]

For more Practice: Solve these Related Problems:

  • Write a Python program to sort a list of lists first by the sum of their elements and then by the maximum element in each sublist using lambda.
  • Write a Python program to sort a list of lists based on the average value of their elements using lambda.
  • Write a Python program to sort a list of lists by the product of the elements in each sublist using lambda.
  • Write a Python program to sort a list of lists by the count of even numbers in each sublist using lambda.

Go to:


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.

Python Code Editor:

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

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.