Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Sort a List by Length

Python Sort a List by Length

Document Object Reference Manual Python3 Examples

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

print

(

sorted_words

)

Code analysis:

  1. words is a list containing several strings.
  2. sorted() The function sorts the list, andkey=len means sorting by the length of each element.
  3. len is a built-in function that returns the length of a string.
  4. sorted_words is the new sorted list.
  5. 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.

Document Object Reference Manual Python3 Examples