How to sort a list of strings in Python
In this article, we will explore various methods to sort a list of strings in Python. The simplest approach is by using sort().
Using sort() Method
The sort() method sorts a list in place and modifying the original list directly.
a = ["banana", "apple", "cherry"]
# Sorting list in place
a.sort()
print(a)
Output
['apple', 'banana', 'cherry']
Explanation:
- a.sort() sorts the original list by modifying it.
- Strings are sorted lexicographically (dictionary order).
Table of Content
Using sorted() Function
The sorted() function returns a new sorted list containing all the items from the original list.
a = ["banana", "apple", "cherry"]
# Sorting the list
res = sorted(a)
print(res)
Output
['apple', 'banana', 'cherry']
Explanation:
- sorted(a) creates a new sorted list without modifying the original a.
- Strings are sorted lexicographically (dictionary order).
Note: The main difference between sort() and sorted() is that sort() modifies the list in place without returning a new list, while sorted() creates a new sorted list from any iterable without modifying the original.
Sorting in Reverse Order
To sort strings in descending order, we can use the reverse=True parameter.
a = ["banana", "apple", "cherry"]
# Sorting in reverse order
res = sorted(a, reverse=True)
print(res)
Output
['cherry', 'banana', 'apple']
Case-Insensitive Sorting
String sorting in Python is case-sensitive by default. To perform a case-insensitive sort, we can use the key=str.lower parameter in sorted() function.
a = ["Banana", "apple", "Cherry"]
res = sorted(a, key=str.lower)
print(res)
Output
['apple', 'Banana', 'Cherry']
Explanation: key=str.lower ensures that sorting is performed based on lowercase equivalents of strings.
Sorting by String Length
We can sort a list of strings by their lengths using the key=len parameter in sorted() function.
a = ["banana", "apple", "kiwi"]
# Sorting by length
res = sorted(a, key=len)
print(res)
Output
['kiwi', 'apple', 'banana']
Explanation: key=len sorts the strings based on their length in ascending order.
Sorting using Custom Key
We can also use any custom sorting logic using a key function.
a = ["banana", "apple", "cherry"]
# Sorting by last character
res = sorted(a, key=lambda s: s[-1])
print(res)
Output
['banana', 'apple', 'cherry']
Explanation: lambda s: s[-1] extracts the last character of each string for comparison.