Python - Ways to sort list of strings in case-insensitive manner
Sorting strings in a case-insensitive manner ensures that uppercase and lowercase letters are treated equally during comparison. To do this we can use multiple methods like sorted(), str.casefold(), str.lower() and many more.
For example we are given a list of string s = ["banana", "Apple", "cherry"] we need to sort the list in such a way that the list become something like ["Apple" ,"banana", "cherry"].
Using sorted() with str.lower
sorted() function can be used with the key parameter set to str.lower to perform a case-insensitive sort.
# List of strings to be sorted
s = ["banana", "Apple", "cherry"]
# Sort the list of strings in a case-insensitive manner
sorted_strings = sorted(s, key=str.lower)
print(sorted_strings)
Output
['Apple', 'banana', 'cherry']
Explanation:
Sorted()function sorts thestringslist in ascending order while preserving the original list.Key=str.lowerensures case-insensitive sorting by converting each string to lowercase for comparison, resulting in['Apple', 'banana', 'cherry'].
Using str.casefold()
casefold() method is a more aggressive version of lower() and is recommended for case-insensitive comparisons.
# List of strings to be sorted
s = ["Banana", "apple", "Cherry"]
# Sort the list of strings in a case-insensitive manner using `str.casefold`
a = sorted(s, key=str.casefold)
print(a)
Output
['apple', 'Banana', 'Cherry']
Explanation:
sorted()Function returns a new sorted list; the original remains unchanged.str.casefoldKey ensures case-insensitive sorting by comparing strings in their lowercase-equivalent form.
Using str.lower()
We can use key str.lower() with sorted to sort the strings in case-insensitve manner.
s = ["Banana", "apple", "Cherry"]
sorted_strings = sorted(s, key=str.lower)
print(sorted_strings) # ['apple', 'Banana', 'Cherry']
Output
['apple', 'Banana', 'Cherry']
Explanation:
sorted()function creates a new sorted list without altering the original.key=str.lowerconverts each string to lowercase for comparison, enabling case-insensitive sorting.
With lambda
Lambda functions can be used with key casefold to sort list in case-insensitve manner
# List of strings to be sorted
s = ["Banana", "apple", "Cherry"]
# Sort the list of strings in a case-insensitive manner using `str.casefold`
a = sorted(s, key=str.casefold)
print(a)
Output
['apple', 'Banana', 'Cherry']
Explanation:
sorted()function returns a new sorted list, leaving the original list unchanged.key=lambda x: x.lower()uses a custom lambda function to convert each string to lowercase for case-insensitive sorting.