Python natsorted() Function
Last Updated :
04 Mar, 2025
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.
Python
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:
Python
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.
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:
Python
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.
Python
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.
Python
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.
Python
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.
Similar Reads
Python sorted() Function
sorted() function returns a new sorted list from the elements of any iterable like (e.g., list, tuples, strings ). It creates and returns a new sorted list and leaves the original iterable unchanged. Let's start with a basic example of sorting a list of numbers using the sorted() function. [GFGTABS]
3 min read
Numpy recarray.partition() function | Python
In numpy, arrays may have a data-types containing fields, analogous to columns in a spreadsheet. An example is [(a, int), (b, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['a'] and arr['b']. Record array
3 min read
Numpy MaskedArray.argsort() function | Python
In many circumstances, datasets can be incomplete or tainted by the presence of invalid data. For example, a sensor may have failed to record a data, or recorded an invalid value. The numpy.ma module provides a convenient way to address this issue, by introducing masked arrays.Masked arrays are arra
3 min read
Python Functools - total_ordering()
Functools module in python helps in implementing higher-order functions. Higher-order functions are dependent functions that call other functions. Total_ordering provides rich class comparison methods that help in comparing classes without explicitly defining a function for it. So, It helps in the r
2 min read
Python Dictionary Exercise
Basic Dictionary ProgramsPython | Sort Python Dictionaries by Key or ValueHandling missing keys in Python dictionariesPython dictionary with keys having multiple inputsPython program to find the sum of all items in a dictionaryPython program to find the size of a DictionaryWays to sort list of dicti
3 min read
Sort a list in Python without sort Function
Python Lists are a type of data structure that is mutable in nature. This means that we can modify the elements in the list. We can sort a list in Python using the inbuilt list sort() function. But in this article, we will learn how we can sort a list in a particular order without using the list sor
3 min read
numpy.partition() in Python
numpy.partition() function is used to create a partitioned copy of input array with its elements rearranged in such a way that the value of the element in k-th position is in the position it would be in a sorted array. All elements smaller than the k-th element are moved before this element and all
2 min read
Bisect Algorithm Functions in Python
The purpose of Bisect algorithm is to find a position in list where an element needs to be inserted to keep the list sorted. Python in its definition provides the bisect algorithms using the module "bisect" which allows keeping the list in sorted order after the insertion of each element. This is es
5 min read
Python | Pandas Index.argsort()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.argsort() function returns the integer indices that would sort the index.
2 min read
Numpy recarray.argsort() function | Python
In numpy, arrays may have a data-types containing fields, analogous to columns in a spreadsheet. An example is [(a, int), (b, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['a'] and arr['b']. Record array
3 min read