🚀 A blazing fast natural sorting library for Python written in Rust 🦀
pip install natsort-rs
from natsort_rs import natsortitems = ['item 1', 'item 10', 'item 3']
print(natsort(items))
# ['item 1', 'item 3', 'item 10']items = ['Item 1', 'Item 3', 'item 2']
print(natsort(items, ignore_case=True))
# ['Item 1', 'item 2', 'Item 3']items = [
{'name': 'item 1', 'id': 1},
{'name': 'item 3', 'id': 3},
{'name': 'item 2', 'id': 2}
]
print(natsort(items, key=lambda d: d['name']))
# [{'name': 'item 1', 'id': 1}, {'name': 'item 2', 'id': 2}, {'name': 'item 3', 'id': 3}]The return type is inferred based on the input list type, so no casting is needed:
items: list[str] = ['item 1', 'item 10', 'item 3']
result = natsort(items)
# result is list[str]
items_int: list[int] = [10, 3, 1]
result_int = natsort(items_int)
# result_int is list[int]This can be helpful if you only want to get the sorted indices returned, that makes the performance-critical part useful for custom sorting use cases:
items = ['item 1', 'item 10', 'item 3']
print(natsort(items, return_indices=True))
# [0, 2, 1]| No. of items | Duration natsort [s] | Duration natsort-rs [s] | Relative speedup |
|---|---|---|---|
| 10 | 0.00006 | 0.00000 | 16.8 |
| 100 | 0.00094 | 0.00002 | 44.3 |
| 1000 | 0.00281 | 0.00022 | 12.7 |
| 10000 | 0.02835 | 0.00262 | 10.8 |
| 100000 | 0.29712 | 0.03334 | 8.9 |
| 1000000 | 3.31207 | 0.45333 | 7.3 |
Execute benchmark.py to reproduce the results.
To build and test the package locally using uv:
uv run maturin develop --releaseTo run benchmarks:
uv run benchmark.pyThis will compare the performance of natsort-rs against the pure Python natsort library and display results in a table format.
uv run -m unittest discover testsThis Python module is build on top of the natord crate and inspired by natsort.
MIT License