w3resource

Python: Sort each sublist of strings in a given list of lists using lambda


27. Sort Sublists Lambda

Write a Python program to sort each sublist of strings in a given list of lists 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):
    # Use list comprehension to create a new list 'result'
    # Sort each sublist in 'input_list' based on the first element of each sublist
    # The sorted() function is used with a lambda function as the sorting key
    result = [sorted(x, key=lambda x: x[0]) for x in input_list]
    
    # Return the sorted list of lists
    return result

# Create a list of lists named 'color1'
color1 = [["green", "orange"], ["black", "white"], ["white", "black", "orange"]]

# Print the original list 'color1'
print("\nOriginal list:")
print(color1)

# Sort each sublist of 'color1' using the 'sort_sublists' function and print the result
print("\nAfter sorting each sublist of the said list of lists:")
print(sort_sublists(color1))

Sample Output:

Original list:
[['green', 'orange'], ['black', 'white'], ['white', 'black', 'orange']]

After sorting each sublist of the said list of lists:
[['green', 'orange'], ['black', 'white'], ['black', 'orange', 'white']]

For more Practice: Solve these Related Problems:

  • Write a Python program to sort each sublist of integers in descending order using lambda.
  • Write a Python program to sort each sublist of mixed data types by converting each element to a string using lambda.
  • Write a Python program to sort each sublist based on the length of its elements using lambda.
  • Write a Python program to sort each sublist in reverse alphabetical order using lambda.

Go to:


Previous: Write a Python program to create the next bigger number by rearranging the digits of a given number.
Next: Write a Python program to sort a given list of lists by length and value 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.