...
Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM
Machine Learning
Machine Learning
Machine Learning & AI
Manage Data
MLOps
Natural Language Processing
NumPy
Pandas
Polars
PySpark
Python Tips
Python Utilities
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

Using natsort for Intuitive Alphanumeric Sorting in Python

Table of Contents

Using natsort for Intuitive Alphanumeric Sorting in Python

When sorting a list of strings containing numbers, Python’s default sorting algorithm operates lexicographically. This can lead to unexpected results, especially when dealing with measurements or alphanumeric data:

a = ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in']
sorted(a)
['1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '2 ft 7 in']

As you can see, the default sorted() function produces a result that doesn’t align with our intuitive understanding of numerical order. It places ’10 ft 2 in’ before ‘2 ft 11 in’ because it compares the strings character by character.

The natsort library solves this problem by providing natural sorting functionality that handles numbers within strings intelligently.

from natsort import natsorted

a = ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in']
natsorted(a)
['1 ft 5 in', '2 ft 7 in', '2 ft 11 in', '10 ft 2 in']

This makes natsort particularly useful when dealing with alphanumeric data, such as filenames, version numbers, or measurements.

Link to natsort.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran

Seraphinite AcceleratorOptimized by Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.