Python Sort a List by Length
In Python, we can use sorted() The function or the list.sort() method sorts a list. If we want to sort the list by the length of its elements, we can do so by specifying the key parameter.key The parameter accepts a function that is applied to each element of the list, and sorting is based on the function's return value.
Example
Define a list containing strings
words
=
[
"apple"
,
"banana"
,
"kiwi"
,
"cherry"
,
"mango"
]
Use the sorted() function to sort a list by string length
sorted_words
=
sorted
(
words
,
key
=
len
)
Print the sorted list
(
sorted_words
)
Code analysis:
wordsis a list containing several strings.sorted()The function sorts the list, andkey=lenmeans sorting by the length of each element.lenis a built-in function that returns the length of a string.sorted_wordsis the new sorted list.print(sorted_words)Print the sorted list.
Output result:
['kiwi', 'mango', 'apple', 'cherry', 'banana']
In this example, the strings in the list are sorted by length from shortest to longest.
Python3 Examples