Python: Sort each sublist of strings in a given list of lists using 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']]
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
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.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics