Python Sort a List by Length
In Python, we can usesorted()a function orlist.sort()a method to sort a list. If we want to sort by the length of the elements in the list, we can do this by specifyingkeya parameter to achieve it.keyThe parameter accepts a function, which is applied to each element in the list, and the list is sorted according to the return value of the function.
Example
# Define a list containing strings
words = ["apple", "banana", "kiwi", "cherry", "mango"]
# Use the sorted() function to sort the list by string length
sorted_words = sorted(words, key=len)
# Output the sorted list
print(sorted_words)
words = ["apple", "banana", "kiwi", "cherry", "mango"]
# Use the sorted() function to sort the list by string length
sorted_words = sorted(words, key=len)
# Output the sorted list
print(sorted_words)
Code explanation:
wordsis a list containing multiple strings.sorted()The function is used to sort the list,key=lenmeaning sorting is based on the length of each element.lenis a built-in function used to return the length of a string.sorted_wordsis the new sorted list.print(sorted_words)Output the sorted list.
Output result:
['kiwi', 'mango', 'apple', 'cherry', 'banana']
In this example, the strings in the list are sorted from shortest to longest.
Other extensions
Python3 Examples