mrkeyoor.com_
Sat 08 Aug 21:01 UTC
PyPIUtilsupdated 08 Aug 2026

natsort

natsort produces human-expected ordering for strings containing numbers, so file2 comes before file10 instead of after it. It tokenizes values into comparable text and numeric pieces, then exposes sorted-style helpers, reusable key functions, locale-aware ordering, path ordering, real-number parsing, and index utilities. It is a sorting-key toolkit, not a semantic-version parser and not a replacement for deciding the domain-specific order your application means.

Verdict

natsort is worth installing when natural ordering is user-visible and the strings are varied enough that a homegrown regex key will grow bugs. Do not use it as a semantic-version authority or assume locale-sensitive results are portable without PyICU and deployment controls.

API stability5/5natsorted, natsort_keygen, realsorted, humansorted, index_natsorted, order_by_index, and the ns flag enum have been established for years, with os_sorted added in 7.1 rather than replacing older calls. The README documents dropped deprecated APIs, but 8.x users get a compact mature surface with normal sorted-compatible parameters.
Docs5/5The unusually thorough README explains basic behavior, real numbers, locale, paths, custom keys, mixed types, in-place sorting, internals, debugging, command-line use, requirements, optional dependencies, and old API removals. The Read the Docs site adds a full API and explanation of generated keys, making surprising output diagnosable instead of magical.
Maintenance3/5The repository had 1,015 stars, only 8 open issues and PRs, and a push on 2026-08-05, showing ongoing care. However, the latest PyPI release 8.4.0 dates to 2023-06-20. For a mature sorting algorithm that can be acceptable, but current repository requirements may move ahead of what the published package supports.
Ecosystem4/5The API fits Python's sorted and list.sort conventions, supplies reusable key functions and index ordering, has a CLI, and optionally integrates fastnumbers and PyICU. Its scope is intentionally language-local and narrow; it does not define a serialized ordering standard or version model that other languages and databases will automatically reproduce.

Use it if

  • You sort filenames, labels, identifiers, or table columns that contain integers or decimals embedded in text
  • You need one tested implementation for signs, exponents, case handling, paths, locale, and mixed numeric values
  • You want a key function compatible with list.sort, min, max, heapq, or another sorting API
  • You need index-based natural ordering so several related arrays can be rearranged consistently
Skip it if

Setup reality

pip install natsort is pure Python and the 8.4.0 metadata supports Python 3.7 and newer. The base install has no required third-party dependencies. Optional fastnumbers can speed numeric parsing, and PyICU gives humansorted and os_sorted more consistent operating-system-like locale behavior, but PyICU is a compiled extension that may require ICU development libraries when no wheel matches. Without it, natsort falls back to Python's locale module, whose collation depends on installed locales and process configuration; locale availability differs across minimal containers and operating systems. Decide first whether you need ordinary numeric token ordering, signed real-number handling, a user locale, or path semantics, because the convenience functions and ns flags make different choices. natsorted returns a new list just like sorted and does not modify its input. For in-place sorting or repeated sorts, build a key once with natsort_keygen. Natural order is not a universal specification: leading zeros, numeric types, case, accents, NaN, paths, and mixed objects can all need product-specific decisions. The library does not understand semantic-version precedence even if common version strings appear right. Pin the algorithm flags in code and add examples of your actual edge cases to tests rather than accepting whichever ordering looks plausible. If results differ between machines, inspect the generated keys and check locale and PyICU availability before blaming Python's sort, which remains stable and simply compares the keys natsort gives it.

Patterns

Sort strings by embedded numberssort-numbered-strings

from natsort import natsorted

files = ['file10.txt', 'file2.txt', 'file1.txt']
ordered = natsorted(files)
# ['file1.txt', 'file2.txt', 'file10.txt']

natsorted returns a new list and leaves files unchanged, matching the behavior of Python's sorted.

Reverse natural ordersort-descending

ordered = natsorted(['v2', 'v10', 'v1'], reverse=True)

reverse applies to the complete generated key; it is not a semantic-version newest-first calculation.

Recognize signed floats and exponentssort-signed-reals

from natsort import realsorted

values = ['value 5.10', 'value -3', 'value 5.2', 'value 1e2']
ordered = realsorted(values)

realsorted enables signed real-number parsing; ordinary natsorted intentionally makes different sign assumptions.

Ignore letter case while sortingsort-ignore-case

from natsort import natsorted, ns

ordered = natsorted(['a10', 'A2', 'a1'], alg=ns.IGNORECASE)

Python's sort is stable, so values whose normalized keys compare equal keep their original relative order.

Combine real-number and case rulescombine-algorithm-flags

from natsort import natsorted, ns

ordered = natsorted(values, alg=ns.REAL | ns.IGNORECASE)

Flags are bitwise values and can be combined with |; pin the exact combination in tests because each changes tokenization.

Sort human text with locale rulessort-by-user-locale

import locale
from natsort import humansorted

locale.setlocale(locale.LC_ALL, '')
ordered = humansorted(['Z10', 'ä2', 'a1'])

Results depend on the active locale and PyICU availability; set and test the deployment locale explicitly.

Approximate file-manager orderingsort-file-browser-order

import os
from natsort import os_sorted

entries = os_sorted(os.listdir('/srv/uploads'))

PyICU improves matching with common file browsers; fallback locale ordering can differ across operating systems.

Natural-sort records by one fieldsort-by-object-field

from natsort import natsorted

rows = [{'name': 'rack10'}, {'name': 'rack2'}]
ordered = natsorted(rows, key=lambda row: row['name'])

The key should return a supported scalar such as str, int, or float rather than relying on custom-object comparisons.

Generate a reusable in-place sort keysort-list-in-place

from natsort import natsort_keygen, ns

natural_key = natsort_keygen(alg=ns.IGNORECASE)
files.sort(key=natural_key)

Create the key once when sorting repeatedly; inspecting natural_key(value) is also the best way to debug unexpected order.

Apply one natural order to related datareorder-parallel-arrays

from natsort import index_natsorted, order_by_index

labels = ['sample10', 'sample2', 'sample1']
values = [0.8, 0.4, 0.2]
index = index_natsorted(labels)
ordered_labels = order_by_index(labels, index)
ordered_values = order_by_index(values, index)

Keep the index tied to the exact input length and order; changing either array before applying it misaligns the data.

Sort numbers and numeric strings togethersort-mixed-numbers-text

from natsort import natsorted

ordered = natsorted([4.5, '10', 2, 'item3'])

Mixed types are supported, but define expected placement for nonnumeric text in tests rather than assuming a universal human order.

Adapt UTF-8 bytes for natural sortingsort-utf8-bytes

from natsort import as_utf8, natsorted

ordered = natsorted([b'a40', b'a6'], key=as_utf8)

bytes are not officially supported; this helper is appropriate only when the values are valid UTF-8 and the limitations are acceptable.

Alternatives

PackageRegistryPick it when
packagingPyPIYou sort PEP 440 Python package versions and need formal version precedence
semantic-versionPyPIYou need Semantic Versioning parsing, validation, ranges, and precedence
looseversionPyPIYou are replacing the removed distutils LooseVersion behavior for loosely structured versions