![]() |
VOOZH | about |
In this article, we will explore various methods to sort a list of strings in Python. The simplest approach is by using sort().
The sort() method sorts a list in place and modifying the original list directly.
['apple', 'banana', 'cherry']
Explanation:
Table of Content
The sorted() function returns a new sorted list containing all the items from the original list.
['apple', 'banana', 'cherry']
Explanation:
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.
To sort strings in descending order, we can use the reverse=True parameter.
['cherry', 'banana', 'apple']
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.
['apple', 'Banana', 'Cherry']
Explanation: key=str.lower ensures that sorting is performed based on lowercase equivalents of strings.
We can sort a list of strings by their lengths using the key=len parameter in sorted() function.
['kiwi', 'apple', 'banana']
Explanation:key=len sorts the strings based on their length in ascending order.
We can also use any custom sorting logic using a key function.
['banana', 'apple', 'cherry']
Explanation: lambda s: s[-1] extracts the last character of each string for comparison.