Sort a list according to the Length of the Elements in Python program

We have a list of strings and our goal is to sort the list based on the length of strings in the list. We have to arrange the strings in ascending order according to their lengths. We can do this using Python built-in method sort() or function sorted() along with a key.

Let's take an example to see the output −

Input:
strings = ["hafeez", "aslan", "honey", "appi"]

Output:
["appi", "aslan", "honey", "hafeez"]

Using sorted() Function

The sorted() function returns a new sorted list without modifying the original list. We pass len as the key parameter to sort by string length ?

# Initialize the list of strings
strings = ["hafeez", "aslan", "honey", "appi"]

# Using sorted() function with key=len
sorted_list = sorted(strings, key=len)

# Print the original and sorted lists
print("Original list:", strings)
print("Sorted list:", sorted_list)
Original list: ['hafeez', 'aslan', 'honey', 'appi']
Sorted list: ['appi', 'aslan', 'honey', 'hafeez']

Using sort() Method

The sort() method modifies the original list in place and returns None. This is more memory-efficient when you don't need to preserve the original list ?

# Initialize the list of strings
strings = ["hafeez", "aslan", "honey", "appi"]

print("Before sorting:", strings)

# Using sort() method to sort the list in place
strings.sort(key=len)

print("After sorting:", strings)
Before sorting: ['hafeez', 'aslan', 'honey', 'appi']
After sorting: ['appi', 'aslan', 'honey', 'hafeez']

Sorting in Descending Order

To sort by length in descending order, use the reverse=True parameter ?

# Initialize the list of strings
strings = ["hafeez", "aslan", "honey", "appi"]

# Sort in descending order by length
descending_sorted = sorted(strings, key=len, reverse=True)

print("Descending order:", descending_sorted)
Descending order: ['hafeez', 'aslan', 'honey', 'appi']

Comparison

Method Modifies Original? Returns Best For
sorted() No New sorted list Preserving original list
sort() Yes None Memory efficiency

Conclusion

Use sorted() when you need to preserve the original list, and sort() for in-place sorting. Both methods use key=len to sort strings by their length in ascending order.

Updated on: 2026-03-15T17:08:51+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements