Skip to main content

The natsort.natsort() function in the naturalsort package is a very simple alternative to Python’s sorted() function that implements natural order sorting in Python.

Usage

Here’s an example of regular sorting vs. natural order sorting:

>>> # Import the sorted() alternative.
>>> from natsort import natsort
>>>
>>> # This is plain old sorting (what we DON'T want).
>>> sorted(['1', '5', '10', '50'])
['1', '10', '5', '50']
>>>
>>> # This is version sorting (what we DO want).
>>> natsort(['1', '5', '10', '50'])
['1', '5', '10', '50']
>>>
>>> # This covers a previously fixed bug.
>>> natsort(['1.0', '1.5'])
['1.0', '1.5']

Why another natsort module?!

There is already a natsort package available on PyPI, however this package does not implement natural order sorting as I would expect it to work. Given the following example it works correctly:

>>> available_versions = ['1.8.1-r26', '1.8.1-r30', '2.0-r2', '2.0-r7', '2.0-r11']
>>> natsort.natsorted(available_versions)
['1.8.1-r26', '1.8.1-r30', '2.0-r2', '2.0-r7', '2.0-r11']

However look what happens when we add a common prefix; it suddenly changes its mind about what natural order sorting means:

>>> natsort.natsorted(['my-package-%s' % v for v in available_versions])
['my-package-2.0-r2',
 'my-package-2.0-r7',
 'my-package-2.0-r11',
 'my-package-1.8.1-r26',
 'my-package-1.8.1-r30']

This last result is clearly incorrect according to reasonable expectations. The implementation of GNU sort -V agrees with us.

Contact

The latest version of naturalsort is available on PyPI and GitHub. For bug reports please create an issue on GitHub. If you have questions, suggestions, etc. feel free to send me an e-mail at peter@peterodding.com.

License

This software is licensed under the MIT license.

© 2013 Peter Odding.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

naturalsort-1.0.1.tar.gz (3.4 kB view details)

Uploaded Source

File details

Details for the file naturalsort-1.0.1.tar.gz.

File metadata

  • Download URL: naturalsort-1.0.1.tar.gz
  • Upload date:
  • Size: 3.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for naturalsort-1.0.1.tar.gz
Algorithm Hash digest
SHA256 362b59a821f969b74d595a252d2703835c928da7a8658efc819f54276f8c2d05
MD5 f000ff3381b8f87931064d32f75648ea
BLAKE2b-256 b5be93b6269993f1ebcf97b580c9e722d3acff5cc314dfe9f3ffef64f3e96390

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page