Natural Sorting for Python
natsort is a Python library that provides 'natural' sorting capabilities, enabling lists containing numbers (e.g., filenames, version strings) to be sorted numerically rather than strictly lexicographically. It's a versatile tool that handles various data types and offers extensive customization. The current version is 8.4.0, and the library is actively maintained with a regular release cadence.
Warnings
- breaking The default behavior of `natsorted()` changed in version 4.0.0. Prior to 4.0.0, it defaulted to sorting by 'real numbers' (signed floats). From 4.0.0 onwards, it prioritizes proper version number sorting by default.
- breaking Version 8.0.0 introduced type hints throughout the codebase. While generally backward-compatible, this could potentially impact projects with very strict static analysis configurations or unusual introspection needs.
- gotcha `natsorted()` returns a *new* sorted list and does not sort in-place, mimicking Python's built-in `sorted()` function. If you need to sort a list in-place, you must reassign the result or use `list.sort()` with a key.
- gotcha For reliable locale-aware sorting (e.g., using `humansorted` or `alg=ns.LOCALE`), especially on non-Windows systems, installing `PyICU` is highly recommended. Python's standard `locale` module can be inconsistent or produce poor results for special characters.
- gotcha `natsort` explicitly does not support sorting byte strings directly on Python 3 due to the complexities of guessing encoding for comparison. Attempting to sort mixed byte/string lists or raw byte lists may lead to unexpected results or errors.
Install
-
pip install natsort
Imports
- natsorted
from natsort import natsorted
- natsort_keygen
from natsort import natsort_keygen
- ns
from natsort import ns
- os_sorted
from natsort import os_sorted
- humansorted
from natsort import humansorted
- realsorted
from natsort import realsorted
Quickstart
from natsort import natsorted unsorted_list = ['file1.txt', 'file10.txt', 'file2.txt', 'file_2.jpeg', 'file_1.png', 'file_10.gif'] sorted_list = natsorted(unsorted_list) print(sorted_list) # Expected output: ['file_1.png', 'file1.txt', 'file_2.jpeg', 'file2.txt', 'file_10.gif', 'file10.txt']