The natsorted() function helps sort objects in natural order, making it ideal for strings with numbers. Unlike sorted() function, which sorts lexicographically, natsorted() arranges strings in a way that is more natural to human intuition. In this article we will understand how to use natsorted() to sort naturally ordered data.
Let's understand the difference between the sorted() and natsorted() for naturally ordered data with an example.
a = ['a10', 'a2', 'b5', 'b21', 'm', 'a']
s = sorted(a) # Sort using regular sort()
print(s)
Output
['a', 'a10', 'a2', 'b21', 'b5', 'm']
Without natsort, the lexicographic sorting results in 'a10' coming before 'a2' and 'b21' coming before 'b5', which may not be the desired order. Now, let's use natsorted:
from natsort import natsorted
a = ['a10', 'a2', 'b5', 'b21', 'm', 'a']
s = natsorted(a) # Sort using natsorted
print(s)
Output
['a', 'a10', 'a2', 'b21', 'b5', 'm']
With natsorted, the list is sorted based on the natural order of the embedded numbers, resulting in a more intuitive ordering of the fruit names.
This showcases how natsort can be applied to various scenarios where strings contain embedded numerical values, providing a more human-friendly sorting order.
Syntax for natsorted()
Syntax : natsorted(iterable, key=None, alg=ns.PATH, signed=False, **kwargs)
Parameters:
- iterable: Collection to be sorted.
- key: (Optional) Function for comparison key.
- alg: (Optional) Sorting algorithm (Default: ns.PATH).
- signed: (Optional) Considers sign of numeric components (True/False).
- kwargs: Extra parameters for sorting.
Return Type: natsorted() returns a sorted list with the same element types as the input iterable.
Working of natsort
Lets discuss what is the internal working of natsort and what are its features,
- Tokenization: natsort breaks strings into alphanumeric chunks, separating numbers from text.
- Numeric Conversion: extracted numeric parts are converted into actual integers or floats for proper numerical comparison.
- Case Handling: it ensures case-insensitive sorting by default, treating "Apple" and "apple" equally unless specified otherwise.
- Sorting Algorithm: uses Python’s Timsort but applies natural ordering rules instead of pure lexicographic comparison.
- Customization Options: supports advanced sorting features like locale-aware sorting, signed numbers, and decimal handling.
Table of Content
Installation
To use natsort(), we first need to install the natsort module in our system. To install it, run the following command in the terminal:
pip install natsort
Now lets's discuss some frequent use cases of natsort() with examples,
Sorting Version Strings
natsort() can be used to sort a list of version strings, here's how:
from natsort import natsorted
a = ["1.21", "1.9", "1.10", "1.2"]
s = natsorted(a)
print(s)
Output
['1.2', '1.9', '1.10', '1.21']
Sorting Mixed Alphanumeric Strings
Alphanumeric strings contain both letters and numbers, making them challenging to sort using traditional sorting functions. The natsorted() function simplifies this process by sorting them naturally and efficiently.
from natsort import natsorted
a = ["a20", "a3", "a100", "a1", "a10"]
s = natsorted(a)
print(s)
Output
['a1', 'a3', 'a10', 'a20', 'a100']
Sorting Paths and Filenames
Sorting file paths can be tricky because they often contain folders and numbers that need proper ordering. natsorted() helps organize them naturally.
from natsort import natsorted
# List of file paths
p = [
"folder1/file10.txt",
"folder1/file2.txt",
"folder1/file1.txt",
"folder2/file20.txt"
]
# Sorting paths naturally
s = natsorted(p)
Output
['folder1/file1.txt', 'folder1/file2.txt', 'folder1/file10.txt', 'folder2/file20.txt']
Sorting Mixed Data Types
When sorting a list that contains both numbers and strings, natsorted() automatically differentiates them and sorts them correctly, whereas sorted() would typically raise an error.
from natsort import natsorted
a = ['a', 10, 'b', 2, 'c', 1]
s = natsorted(a)
print(s)
Output
[1, 2, 10, 'a', 'b', 'c']
Explanation: natsorted() correctly sorts numerical values first before arranging the strings alphabetically.