Python: Sort each sublist of strings in a given list of lists
Python List: Exercise - 95 with Solution
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:
Python Code Editor:
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.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-95.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics