0
0
PythonHow-ToBeginner · 3 min read

How to Sort List of Strings by Length in Python

To sort a list of strings by length in Python, use the sorted() function or the list's sort() method with the key=len argument. This tells Python to order the strings based on their length instead of alphabetical order.
📐

Syntax

You can sort a list of strings by length using either the sorted() function or the list's sort() method. Both accept a key parameter where you specify len to sort by string length.

  • sorted(list_of_strings, key=len): Returns a new sorted list without changing the original.
  • list_of_strings.sort(key=len): Sorts the list in place, modifying the original list.
python
sorted_list = sorted(list_of_strings, key=len)
list_of_strings.sort(key=len)
💻

Example

This example shows how to sort a list of strings by their length using both sorted() and list.sort(). It prints the original list, the sorted copy, and the list after in-place sorting.

python
words = ['apple', 'banana', 'fig', 'cherry', 'date']

# Using sorted() to get a new sorted list
sorted_words = sorted(words, key=len)
print('Sorted with sorted():', sorted_words)

# Using list.sort() to sort in place
words.sort(key=len)
print('Sorted with list.sort():', words)
Output
Sorted with sorted(): ['fig', 'date', 'apple', 'cherry', 'banana'] Sorted with list.sort(): ['fig', 'date', 'apple', 'cherry', 'banana']
⚠️

Common Pitfalls

One common mistake is forgetting to use the key=len argument, which causes Python to sort strings alphabetically instead of by length. Another is confusing sorted() and list.sort(): sorted() returns a new list, while list.sort() changes the original list.

python
# Wrong: sorts alphabetically, not by length
words = ['apple', 'banana', 'fig']
print(sorted(words))  # ['apple', 'banana', 'fig']

# Right: sorts by length
print(sorted(words, key=len))  # ['fig', 'apple', 'banana']
Output
['apple', 'banana', 'fig'] ['fig', 'apple', 'banana']
📊

Quick Reference

MethodDescriptionModifies Original List?
sorted(list, key=len)Returns a new list sorted by string lengthNo
list.sort(key=len)Sorts the list in place by string lengthYes

Key Takeaways

Use the key=len argument to sort strings by their length.
sorted() returns a new sorted list without changing the original.
list.sort() sorts the list in place and changes the original list.
Without key=len, strings sort alphabetically, not by length.
Choose sorted() or list.sort() based on whether you want to keep the original list unchanged.