08-16-2023, 08:49 AM
[Tut] 5 Effective Methods to Sort a List of String Numbers Numerically in Python
5/5 – (1 vote)
Problem Formulation
Sorting a list of string numbers numerically in Python can lead to unexpected issues.
For example, using the naive approach to sort the list using will result in the incorrect order as it sorts the list of strings lexicographically, not numerically.
In this short article, my goal is to present the five best methods to correctly sort this list numerically. My recommended approach is the fifth one, see below.![[Image: 1f447.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png)
Method 1: Convert Strings to Integers and Sort
This method involves converting each string in the list to an integer and then sorting them. It’s a direct and simple approach to ensure numerical ordering.
Output:
Recommended: Python List Comprehension
Method 2: Using the Parameter with sort()
This method uses the parameter with the function to sort the strings as integers. It allows for numerical comparison without altering the original strings.
Output:
Recommended: Python with key parameter
Method 3: Using the natsort Module
The module provides a natural sorting algorithm, useful for sorting strings that represent numbers. This method can handle more complex string sorting scenarios.
Output:
Method 4: Using Regular Expressions
Using regular expressions, this method can sort strings containing both letters and numbers. It converts the numeric parts into floats for comparison, handling mixed content.
Output:
Recommended: Python Regular Expression Superpower
Method 5: Using sorted() with key Parameter (Recommended)
This method combines the simplicity of using the parameter with the benefit of creating a new sorted list, leaving the original untouched. It’s concise and effective.
Output:
Recommended: Python function
Summary – When to Use Which
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
![[Image: 3D_cover-1024x944.jpg]](https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg)
Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
Get your Python One-Liners on Amazon!!
5/5 – (1 vote)
Problem Formulation
Sorting a list of string numbers numerically in Python can lead to unexpected issues.
For example, using the naive approach to sort the list
Code:
lst = ["1", "10", "3", "22", "23", "4", "2", "200"]Code:
lst.sort()In this short article, my goal is to present the five best methods to correctly sort this list numerically. My recommended approach is the fifth one, see below.
![[Image: 1f447.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png)
Method 1: Convert Strings to Integers and Sort
This method involves converting each string in the list to an integer and then sorting them. It’s a direct and simple approach to ensure numerical ordering.
Code:
lst = [int(x) for x in lst]
lst.sort()Output:
Code:
['1', '2', '3', '4', '10', '22', '23', '200']
Recommended: Python List ComprehensionMethod 2: Using the
Code:
keyThis method uses the
Code:
keyCode:
intCode:
lst.sort(key=int)Output:
Code:
['1', '2', '3', '4', '10', '22', '23', '200']
Recommended: Python Code:
list.sort()Method 3: Using the natsort Module
The
Code:
natsortCode:
from natsort import natsorted
lst = natsorted(lst)Output:
Code:
['1', '2', '3', '4', '10', '22', '23', '200']Method 4: Using Regular Expressions
Using regular expressions, this method can sort strings containing both letters and numbers. It converts the numeric parts into floats for comparison, handling mixed content.
Code:
import re def sort_human(l): convert = lambda text: float(text) if text.isdigit() else text alphanum = lambda key: [convert(c) for c in re.split('([-+]?[0-9]*\.?[0-9]*)', key)] l.sort(key=alphanum) return l lst = sort_human(lst)Output:
Code:
['1', '2', '3', '4', '10', '22', '23', '200']
Recommended: Python Regular Expression SuperpowerMethod 5: Using sorted() with key Parameter (Recommended)
This method combines the simplicity of using the
Code:
keyCode:
lst = sorted(lst, key=int)Output:
Code:
['1', '2', '3', '4', '10', '22', '23', '200']
Recommended: Python Code:
sorted()Summary – When to Use Which
- Method 1: Converts strings to integers, then sorts. Simple but alters the original list.
- Method 2: Uses the parameter withCode:
keyfor sorting. Preserves the original strings.Code:int
- Method 3: Utilizes the module. Handles complex scenarios.Code:
natsort
- Method 4: Employs regular expressions for sorting alphanumeric strings.
- Method 5 (Recommended): Combines the simplicity of using withCode:
key. Preserves the original list and offers concise code.Code:sorted()
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
![[Image: 3D_cover-1024x944.jpg]](https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg)
Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
- Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
- Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
Get your Python One-Liners on Amazon!!

