Open In App

Python | Ways to sort list of strings in case-insensitive manner

Last Updated : 26 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list of strings, A task is to sort the strings in a case-insensitive manner. Given below are a few methods to solve the task. 

Method #1: Using casefold() 

Python3




# Python code to demonstrate to sort list of
# strings in case insensitive manner
 
# Initialising list
ini_list = ['akshat', 'garg', 'GeeksForGeeks', 'Alind',
            'SIngh', 'manjeet', 'Munich']
 
# Sorting list in case sensitive manner
res1 = sorted(ini_list)
 
# Printing case-sensitive
print("Case-sensitive sorted list", str(res1))
 
# Sorting list in case-insensitive manner
res2 = sorted(ini_list, key=lambda s: s.casefold())
 
# Printing case-senstive sorted list
print("Case-insensitive sorted list", str(res2))


Output

Case-sensitive sorted list ['Alind', 'GeeksForGeeks', 'Munich', 'SIngh', 'akshat', 'garg', 'manjeet']
Case-insensitive sorted list ['akshat', 'Alind', 'garg', 'GeeksForGeeks', 'manjeet', 'Munich', 'SIngh']

Time Complexity: O(nlogn)
Space Complexity: O(n)

Method #2: Using lower() 

Python3




# Python code to demonstrate
# to sort list of
# strings in case insensitive manner
 
# Initialising list
ini_list = ['akshat', 'garg', 'GeeksForGeeks', 'Alind',
            'SIngh', 'manjeet', 'Munich']
 
# Sorting list in case sensitive manner
ini_list.sort()
 
# Printing case-sensitive
print("Case-sensitive sorted list", str(ini_list))
 
# Sorting list in case-insensitive manner
ini_list.sort(key=lambda x: x.lower())
 
# Printing result
print("Case-insensitive sorted list", str(ini_list))


Output

Case-sensitive sorted list ['Alind', 'GeeksForGeeks', 'Munich', 'SIngh', 'akshat', 'garg', 'manjeet']
Case-insensitive sorted list ['akshat', 'Alind', 'garg', 'GeeksForGeeks', 'manjeet', 'Munich', 'SIngh']

Time Complexity: O(nlogn)
Space Complexity: O(n)

Method #3: Using sort() method and str.lower() method:

Approach:

  1. In this example, we have a strings list containing five strings with different casing. 
  2. We pass this list as an argument to the sort_strings_case_insensitive() function.
  3. Now store the result in the sorted_strings variable. 
  4. Finally, we print the sorted_strings variable to see the resulting sorted list in a case-insensitive manner.

Example:

Python3




def sort_strings_case_insensitive(strings):
 
    strings.sort(key=str.lower)
    return strings
 
 
# input string
strings = ["apple", "Banana", "CHERRY", "durian", "EGGFRUIT"]
 
sorted_strings = sort_strings_case_insensitive(strings)
 
# Printing sorted string
print(sorted_strings)


Output

['apple', 'Banana', 'CHERRY', 'durian', 'EGGFRUIT']

Time Complexity: O(n log n), where n is the length of the list
Auxiliary Space: O(1)

Method #4: Use the merge sort algorithm with a key function to sort the list in a case-insensitive manner. The key function takes a string and returns its lowercase version, which will be used to compare the strings during the sorting process.

Here are the steps to implement this method:

  1. Define a merge_sort function that takes a list and a key function as arguments.
  2. If the length of the list is less than or equal to 1, return the list.
  3. Divide the list into two halves and recursively call merge_sort on each half.
  4. Merge the two sorted halves by comparing the elements using the key function.
  5. Return the merged list.
  6. Call the merge_sort function with the initial list and the key function as lambda x: x.lower().
  7. Print the sorted list.

Python3




# Python code to demonstrate to sort list of
# strings in case insensitive manner
 
# Define merge_sort function with key function
def merge_sort(lst, key):
   
    # base-case
    if len(lst) <= 1:
        return lst
       
      # merge-sort logic
    mid = len(lst) // 2
    left = merge_sort(lst[:mid], key)
    right = merge_sort(lst[mid:], key)
     
    return merge(left, right, key)
 
# Define merge function to merge
# two sorted lists using key function
def merge(left, right, key):
    result = []
     
    i, j = 0, 0
     
    while i < len(left) and j < len(right):
        
        if key(left[i]) <= key(right[j]):
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    result += left[i:]
    result += right[j:]
     
    return result
 
# Initialising list
ini_list = ['akshat', 'garg', 'GeeksForGeeks', 'Alind',
            'SIngh', 'manjeet', 'Munich']
 
# Sorting list in case insensitive manner
# using merge_sort with key function
res = merge_sort(ini_list, key=lambda x: x.lower())
 
# Printing result
print("Case-insensitive sorted list:", res)


Output

Case-insensitive sorted list: ['akshat', 'Alind', 'garg', 'GeeksForGeeks', 'manjeet', 'Munich', 'SIngh']

Time complexity: O(n log n) 
Auxiliary space: O(n).

Method #5: Comparing each element and placing at their correct position.

Sort the list in a case-insensitive manner by comparing the lowercase versions of the strings using the lower() method.

Python3




# Python code to demonstrate
# to sort list of
# strings in case insensitive manner
 
# Initialising list
ini_list = ['akshat', 'garg', 'GeeksForGeeks', 'Alind',
            'SIngh', 'manjeet', 'Munich']
 
# Sorting list in case-sensitive manner using bubble sort
for i in range(len(ini_list)):
   
    for j in range(i+1, len(ini_list)):
       
        if ini_list[j].lower() < ini_list[i].lower():
            ini_list[i], ini_list[j] = ini_list[j], ini_list[i]
 
# Printing case-sensitive
print("Case-sensitive sorted list", str(sorted(ini_list)))
 
# Printing case-insensitive sorted list using bubble sort
print("Case-insensitive sorted list using bubble sort", str(ini_list))


Output

Case-sensitive sorted list ['Alind', 'GeeksForGeeks', 'Munich', 'SIngh', 'akshat', 'garg', 'manjeet']
Case-insensitive sorted list using bubble sort ['akshat', 'Alind', 'garg', 'GeeksForGeeks', 'manjeet', 'Munich', 'SIngh']

Time complexity: O(n * n) 
Auxiliary space: O(n)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads