Sort Numeric Strings in a List - Python
Last Updated :
12 Feb, 2025
Improve
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.
Using sorted()
We use Python's built-in sorted() function along with the key=int parameter as this converts each element to an integer for comparison during sorting.
a = ["10", "2", "30", "4"]
# Sort the list by converting each element to int during comparison
res = sorted(a, key=int)
print(res)
Output
['2', '4', '10', '30']
Explanation:
- key=int argument tells sorted() to convert each string to an integer before comparing them ensuring numerical order.
- sorted list res contains the numeric strings arranged as ["2", "4", "10", "30"].
Using list.sort()
We sort the list in-place using the sort() method with the same key=int parameter.
a = ["10", "2", "30", "4"]
# In-place sorting using key=int
a.sort(key=int)
print(a)
Output
['2', '4', '10', '30']
Explanation:
- sort() method modifies the original list, like Method 1 key=int ensures that the elements are compared as integers.
- original list a is updated to ["2", "4", "10", "30"].
Naive Approach Using Nested Loops
We implement a selection sort (or bubble sort) by using nested loops that compare elements by converting them to integers during each comparison.
a = ["10", "2", "30", "4"]
# Naive approach: using nested loops to sort the list in-place
for i in range(len(a)):
for j in range(i + 1, len(a)):
if int(a[i]) > int(a[j]):
a[i], a[j] = a[j], a[i]
print(a)
Output
['2', '4', '10', '30']
Explanation:
- For each element, the inner loop compares it with every subsequent element and int() conversion happens during each comparison to ensure numerical order.
- If an element is found to be greater than a later element (numerically) then they are swapped.