Open In App

Sort Numeric Strings in a List - Python

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Python
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.

Python
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.

Python
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.

Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy