Python - Ways to sort list of strings in case-insensitive manner
Last Updated :
12 Jul, 2025
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.
Python
# 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 the strings
list in ascending order while preserving the original list.Key=str.lower
ensures 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.
Python
# 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.casefold
Key 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.
Python
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.lower
converts 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
Python
# 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.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice