Quick Start

Getting started with natsort is incredibly intuitive. The primary function you will use is natsorted(), which acts as a natural, drop-in replacement for Python's built-in sorted() function.

Hello World: Basic Sorting

In standard Python, sorting strings containing numbers results in lexicographical ordering. natsorted() fixes this instantly.

from natsort import natsorted

# A list of strings containing integer numbers
data = ['item-10', 'item-2', 'item-1']

# Standard Python sorting (Lexicographical)
print(sorted(data))
# Output: ['item-1', 'item-10', 'item-2']

# Natural sorting with natsort
print(natsorted(data))
# Output: ['item-1', 'item-2', 'item-10']

Sorting Complex Objects (Dictionaries, Tuples, Classes)

Just like Python's sorted(), natsorted() accepts a key argument. This is essential when your data isn't a flat list of strings, but rather a collection of complex objects, dictionaries, or tuples.

from natsort import natsorted

servers = [
    {"name": "server-10.example.com", "uptime": 90},
    {"name": "server-2.example.com",  "uptime": 14},
    {"name": "server-1.example.com",  "uptime": 365}
]

# Sort the dictionaries based on the 'name' key
sorted_servers = natsorted(servers, key=lambda x: x["name"])

for server in sorted_servers:
    print(server["name"])

# Output:
# server-1.example.com
# server-2.example.com
# server-10.example.com

Reversing the Sort Order

If you need the items in descending order, pass reverse=True.

from natsort import natsorted

data = ['v1', 'v10', 'v2']
print(natsorted(data, reverse=True))
# Output: ['v10', 'v2', 'v1']

Sorting In-Place for Memory Efficiency

natsorted() returns a new list, which consumes additional memory. If you are dealing with massive datasets (e.g., millions of strings) and want to sort the list in-place, you should use the list.sort() method combined with natsort_keygen().

Under the hood, natsort_keygen() generates the exact closure (function) that natsorted uses to parse strings.

from natsort import natsort_keygen

data = ['version-1.9', 'version-2.0', 'version-1.11']

# Generate a natural sorting key
natsort_key = natsort_keygen()

# Sort the list in-place (mutates the original list)
data.sort(key=natsort_key)

print(data)
# Output: ['version-1.9', 'version-1.11', 'version-2.0']

Common Pitfalls for Beginners

  1. Forgetting assignment: natsorted() does not modify the list in place. natsorted(my_list) will return the sorted list but leave my_list untouched. You must assign it: my_list = natsorted(my_list).
  2. Using the wrong key: If you use key=natsort_keygen() with natsorted(), you are doing redundant work. natsorted(data) already applies the key generator internally. Only use natsort_keygen() when utilizing list.sort().

Ready for more? Explore the Usage Guide to handle file paths, negative numbers, decimals, and custom algorithms!