Sorting a list of strings by their length in Python can be accomplished using the built-in sorted() function or the .sort() method available for lists. Below are the steps and examples demonstrating both approaches.
Using the sorted() Function
The sorted() function returns a new sorted list from the elements of any iterable (like a list). By default, it sorts items in ascending order. To sort based on the length of the strings, you can use the key parameter.
# Sample list of strings
strings = ["apple", "banana", "kiwi", "cherry", "blueberry"]
# Sort the list by length of strings
sorted_strings = sorted(strings, key=len)
# Output the result
print(sorted_strings)
Using the .sort() Method
The .sort() method sorts the list in place and modifies the original list. Just like sorted(), it also accepts a key parameter.
# Sample list of strings
strings = ["apple", "banana", "kiwi", "cherry", "blueberry"]
# Sort the list by length of strings in place
strings.sort(key=len)
# Output the sorted list
print(strings)
Sorting in Descending Order
If you need to sort the list in descending order based on the length of the strings, you can add the reverse=True argument.
Using sorted()
# Sort the list by length of strings in descending order
sorted_strings_desc = sorted(strings, key=len, reverse=True)
print(sorted_strings_desc)
Using .sort()
# Sort the list by length of strings in descending order in place
strings.sort(key=len, reverse=True)
print(strings)
Summary
Sorting strings by their length in Python is straightforward with either the sorted() function or the .sort() method. The flexibility offered by the key parameter allows for easy manipulation of the sorting criteria, catering to varying requirements such as ascending or descending order based on string length. This functionality is particularly useful in data processing and manipulation tasks where string datasets need to be organized efficiently.