w3resource

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


Sort Strings in Sublists

Write a Python program to sort each sublist of strings in a given list of lists.

Sample Solution:

Python Code:

# Define a function 'sort_sublists' that sorts each sublist in 'input_list'
def sort_sublists(input_list):
    # Use the 'map' function to sort each sublist in 'input_list' and convert the result to a list
    result = list(map(sorted, input_list))
    return result

# Create a list 'color1' containing sublists of colors
color1 = [["green", "orange"], ["black", "white"], ["white", "black", "orange"]]

# Print a message indicating the original list
print("\nOriginal list:")
# Print the contents of 'color1'
print(color1)
# Print a message indicating the sorted sublists of the list
print("\nAfter sorting each sublist of the said list of lists:")
# Call the 'sort_sublists' function with 'color1' and print the result
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']]

Flowchart:

Flowchart: Sort each sublist of strings in a given list of lists.

For more Practice: Solve these Related Problems:

  • Write a Python program to sort a list of lists alphabetically.
  • Write a Python program to sort sublists based on their second element.
  • Write a Python program to sort lists of lists while maintaining relative order.
  • Write a Python program to sort sublists with a mix of numbers and strings.

Go to:


Previous: Write a Python program to count number of unique sublists within a given list.
Next: Write a Python program to sort a given list of lists by length and value.

Python Code Editor:

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.