Sort mixed list in Python
Last Updated :
26 Apr, 2023
Sometimes, while working with Python, we can have a problem in which we need to sort a particular list that has mixed data types. That it contains integers and strings and we need to sort each of them accordingly. Let's discuss certain ways in which this problem can be solved.
Method #1: Using sort() + comparator This problem can be solved using sort functionality provided by Python. We can construct our own custom comparator to complete the task of mixed sort.
Python3
# Python3 code to demonstrate working of
# Sort Mixed List
# using sort() + comparator
# comparator function for sort
def mixs(num):
try:
ele = int(num)
return (0, ele, '')
except ValueError:
return (1, num, '')
# initialize list
test_list = [4, 'gfg', 2, 'best', 'is', 3]
# printing original list
print("The original list : " + str(test_list))
# Sort Mixed List
# using sort() + comparator
test_list.sort(key = mixs)
# printing result
print("List after mixed sorting : " + str(test_list))
Output : The original list : [4, 'gfg', 2, 'best', 'is', 3]
List after mixed sorting : [2, 3, 4, 'best', 'gfg', 'is']
Time complexity: O(n*log(n)), where "n" is the number of elements in the list, as sorting the list involves calling the sorting algorithm which has a time complexity of O(n log(n)).
Auxiliary space: O(1), as the sorting is done in place, i.e., no extra memory is used to store a sorted list.
Method #2 : Using sorted() + key + lambda + isdigit() The combination of above functionalities can also be used to achieve solution to this problem. In this, we just sort the list using sorted() using key functionality using lambda function to segregate digits using isdigit().
Python3
# Python3 code to demonstrate working of
# Sort Mixed List
# using sorted() + key + lambda + isdigit()
# initialize list
test_list = ['4', 'gfg', '2', 'best', 'is', '3']
# printing original list
print("The original list : " + str(test_list))
# Sort Mixed List
# using sorted() + key + lambda + isdigit()
res = sorted(test_list, key = lambda ele: (0, int(ele))
if ele.isdigit() else (1, ele))
# printing result
print("List after mixed sorting : " + str(res))
Output : The original list : ['4', 'gfg', '2', 'best', 'is', '3']
List after mixed sorting : ['2', '3', '4', 'best', 'gfg', 'is']
Time Complexity: O(n*nlogn) where n is the number of elements in the string list. The sort() + comparator is used to perform the task and it takes O(n*nlogn) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the string list.
Method #3 : Using isnumeric(),sort() and extend() methods
Python3
# Python3 code to demonstrate working of
# Sort Mixed List
# initialize list
test_list = ['4', 'gfg', '2', 'best', 'is', '3']
# printing original list
print("The original list : " + str(test_list))
# Sort Mixed List
res = []
x=[]
for i in test_list:
if i.isnumeric():
res.append(i)
else:
x.append(i)
res.sort()
x.sort()
res.extend(x)
# printing result
print("List after mixed sorting : " + str(res))
OutputThe original list : ['4', 'gfg', '2', 'best', 'is', '3']
List after mixed sorting : ['2', '3', '4', 'best', 'gfg', 'is']
Time Complexity : O(N logN)
Auxiliary Space : O(N)
Method #4: Using two loops
Create an empty list to store the sorted values
Loop through the list and append all the numeric values to a separate list
Loop through the list and append all the non-numeric values to the separate list
Sort both lists
Append the sorted non-numeric list to the sorted numeric list
Return the sorted list
Compute the time and auxiliary space complexity
Python3
# Python3 code to demonstrate working of
# Sort Mixed List
# initialize list
test_list = ['4', 'gfg', '2', 'best', 'is', '3']
# printing original list
print("The original list : " + str(test_list))
# Sort Mixed List
numeric_list = []
non_numeric_list = []
for i in test_list:
if i.isnumeric():
numeric_list.append(int(i))
else:
non_numeric_list.append(i)
numeric_list.sort()
non_numeric_list.sort()
sorted_list = []
sorted_list.extend([str(i) for i in numeric_list])
sorted_list.extend(non_numeric_list)
# printing result
print("List after mixed sorting : " + str(sorted_list))
OutputThe original list : ['4', 'gfg', '2', 'best', 'is', '3']
List after mixed sorting : ['2', '3', '4', 'best', 'gfg', 'is']
The time complexity of this approach is O(n log n) because of the two sorting operations, one for the numeric list and one for the non-numeric list.
The auxiliary space complexity is also O(n) because of the separate lists created for the numeric and non-numeric values.
Similar Reads
Sort a list in python Sorting is a fundamental operation in programming, allowing you to arrange data in a specific order. Here is a code snippet to give you an idea about sorting.Python# Initializing a list a = [5, 1, 5, 6] # Sort modifies the given list a.sort() print(a) b = [5, 2, 9, 6] # Sorted does not modify the gi
5 min read
Sort Tuple of Lists in Python The task of sorting a tuple of lists involves iterating through each list inside the tuple and sorting its elements. Since tuples are immutable, we cannot modify them directly, so we must create a new tuple containing the sorted lists. For example, given a tuple of lists a = ([2, 1, 5], [1, 5, 7], [
3 min read
Sort Numeric Strings in a List - Python We are given a list of numeric strings and our task is to sort the list based on their numeric values rather than their lexicographical order. For example, if we have: a = ["10", "2", "30", "4"] then the expected output should be: ["2", "4", "10", "30"] because numerically, 2 < 4 < 10 < 30.
2 min read
Python | Sort Flatten list of list The flattening of list of lists has been discussed earlier, but sometimes, in addition to flattening, it is also required to get the string in a sorted manner. Let's discuss certain ways in which this can be done. Method #1 : Using sorted() + list comprehension This idea is similar to flattening a l
7 min read
Python | Sort a list of percentage Given a list of percentage, write a Python program to sort the given list in ascending order. Let's see different ways to do the task. Code #1: Chops '%' in string and convert it into float. Python3 # Python code to sort list of percentage # List initialization Input =['2.5 %', '6.4 %', '91.6 %', '1
3 min read