Python | Sort list containing alphanumeric values
Last Updated :
09 May, 2023
Given a list containing both alphanumeric values, write a Python program to sort the given list in such a way that the alphabetical values always comes after numeric values. Examples:
Input : ['k', 5, 'e', 3, 'g', 7, 0, 't']
Output : [0, 3, 5, 7, 'e', 'g', 'k', 't']
Input : [1, 'c', 3, 2, 'a', 'b']
Output : [1, 2, 3, 'a', 'b', 'c']
Approach 1 : Using sort() method To use Python sort() method we need to convert all list values to str type first. Now there are two methods to convert values to string.
- Method #1 : List comprehension Python list comprehension can be simply used to convert each element of list to string type. We sort it and since all values are now str type, we change the final list to back to its original form.
Python3
# Python3 program to Sort list
# containing alpha and numeric values
def sort(lst):
lst = [str(i) for i in lst]
lst.sort()
lst = [int(i) if i.isdigit() else i for i in lst ]
return lst
# Driver code
lst = ['k', 5, 'e', 3, 'g', 7, 0, 't']
print(sort(lst))
Output:[0, 3, 5, 7, 'e', 'g', 'k', 't']
- Method #2 : Using key function Key function serves as a key for the sort comparison, which is equal to str in our case.
Python3
# Python3 program to Sort list
# containing alpha and numeric values
def sort(lst):
lst.sort(key = str)
return lst
# Driver code
lst = ['k', 5, 'e', 3, 'g', 7, 0, 't']
print(sort(lst))
Output:[0, 3, 5, 7, 'e', 'g', 'k', 't']
Approach 2 : sorted() Alternatively, you can also use Python's in-built function sorted() for the same purpose. Simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list. Now there are again two ways of using sorted().
- Method #1 : Using key function
Python3
# Python3 program to Sort list
# containing alpha and numeric values
def sort(lst):
return sorted(lst, key = str)
# Driver code
lst = ['k', 5, 'e', 3, 'g', 7, 0, 't']
print(sort(lst))
Output:[0, 3, 5, 7, 'e', 'g', 'k', 't']
Python3
# Python3 program to Sort list
# containing alpha and numeric values
def sort(lst):
return sorted(lst, key = lambda x: (isinstance(x, str), x))
# Driver code
lst = ['k', 5, 'e', 3, 'g', 7, 0, 't']
print(sort(lst))
Output:[0, 3, 5, 7, 'e', 'g', 'k', 't']
Approach#3:Using two lists and concatenation
Algorithm
1. Create two new lists: one for integers and one for strings.
2. Iterate through the original list.
3. For each element in the original list, check if it is a string or integer.
4. If it is a string, append it to the string list.
5. If it is an integer, append it to the integer list.
6. Sort both the integer and string lists.
7. Concatenate the integer and string lists together to create the final result list.
8. Return the final result list.
Python3
def sort_alphanumeric(input_list):
int_list = []
str_list = []
for i in input_list:
if isinstance(i, str):
str_list.append(i)
else:
int_list.append(i)
int_list = sorted(int_list)
str_list = sorted(str_list)
result_list = int_list + str_list
return result_list
input_list = ['k', 5, 'e', 3, 'g', 7, 0, 't']
print(sort_alphanumeric(input_list))
Output[0, 3, 5, 7, 'e', 'g', 'k', 't']
Time Complexity: O(n log n) for the sorted() function.
Space Complexity: O(n) for the int_list and str_list.
Approach#4: Using numpy
Algorithm:
Convert the input list to a numpy array using np.array() function.
Create a boolean mask array which checks whether each element of the array is of str or int type using np.char.isnumeric() function and logical not operator.
Sort the two subcontaining non-numeric elements, using np.sort() function.
Concatenate the two sorted sub-arrays using np.concatenate() function to obtain the final sorted array.
Convert the final sorted array to list using tolist() method.
Approach#4: Using Regular Expression
Algorithm
Create two empty lists, one for integers and one for strings.
Iterate through the original list.
Convert each element to a string using str().
Use regular expressions to check if the string matches a pattern for integer or string.
If the string matches the integer pattern, append it to the integer list.
If the string matches the string pattern, append it to the string list.
Sort both the integer and string lists.
Concatenate the integer and string lists together to create the final result list.
Return the final result list.
Python3
#Python3
import re
def sort_alphanumeric(input_list):
int_list = []
str_list = []
for i in input_list:
s = str(i)
if re.match(r'^\d+$', s):
int_list.append(int(s))
else:
str_list.append(s)
int_list = sorted(int_list)
str_list = sorted(str_list)
result_list = int_list + str_list
return result_list
input_list = ['k', 5, 'e', 3, 'g', 7, 0, 't']
print(sort_alphanumeric(input_list))
Output[0, 3, 5, 7, 'e', 'g', 'k', 't']
Time Complexity: O(n log n) for the sorted() function.
Auxiliary Space: O(n) for the int_list and str_list.
Similar Reads
How to Sort a List Alphabetically in Python? Sorting lists alphabetically is a common task in Python, whether we're organizing names, cleaning data or building an interface. Python makes sorting easy with several built-in methods and libraries for both simple and advanced sorting needs.Let's look at some of the most common methods one by one:U
2 min read
Sort a List of Python Dictionaries by a Value Sorting a list of dictionaries by a specific value is a common task in Python programming. Whether you're dealing with data manipulation, analysis, or simply organizing information, having the ability to sort dictionaries based on a particular key is essential. In this article, we will explore diffe
3 min read
Sorting Python Dictionary With Lists as Values Python offers various methods to sort a dictionary with Lists as Values. This is a common task when dealing with data where you need to order elements based on different criteria. In this article, we will sort a dictionary with lists as values in Python. Sort a Dictionary with Lists as Values in Pyt
3 min read
Python | Check for Descending Sorted List The sorted operation of list is essential operation in many application. But it takes best of O(nlogn) time complexity, hence one hopes to avoid this. So, to check if this is required or not, knowing if list is by default reverse sorted or not, one can check if list is sorted or not. Lets discuss va
3 min read
Python - Sort Dictionary List by Key's ith Index value Given List of dictionaries, sort dictionaries on basis of Key's ith index value Input : [{"Gfg" : "Best", "for" : "Geeks"}, {"Gfg" : "Good", "for" : "Me"}, {"Gfg" : "Better", "for" : "All"}], K = "Gfg", i = 1 Output : [{'Gfg': 'Best', 'for': 'Geeks'}, {'Gfg': 'Better', 'for': 'All'}, {'Gfg': 'Good',
7 min read
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
Ways to Sort List of Float Values - Python Given a list of float values, our task is to sort them in ascending order. For example, given [3.1, 2.4, 5.6, 1.8], the sorted output should be: [1.8, 2.4, 3.1, 5.6]Using sorted()Pythonâs built-in sorted() function sorts the list in ascending order by default. It is efficient and works well for most
2 min read
Sort Dictionary by Value Python Descending Sometimes, we need to sort the dictionary by value in reverse order or descending order. We can perform this task easily by using Python. In this article, we will learn to Sort the Dictionary by Value in Descending Order using Python Programming. Below is an example to understand the problem stateme
4 min read
Python - Sort dictionaries list by Key's Value list index Given list of dictionaries, sort dictionaries on basis of Key's index value. Input : [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}], K = "Gfg", idx = 0 Output : [{'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [
14 min read
Python | Sort alternate numeric and alphabet list Sometimes, while performing sorting in list, we have a problem in which we need to perform particular type of sorting in which we need to sort in alternate ways in which we have numerics and alphabets sorted in order. Lets discuss certain ways in which this task can be performed. Method #1 : Using i
5 min read