Skip to content

lexicographic order

Lexicographic order is a way of ordering sequences by comparing their elements one position at a time, generalizing the alphabetical order of words in a dictionary to any symbols that can be ranked.

The comparison looks at the first element of each sequence. If those elements differ, they alone decide the outcome. If they’re equal, the comparison moves to the next position, and so on. A sequence that runs out while still matching the other is a prefix of it and comes first, which is why "car" sorts before "cart".

Any element type with a defined order works, such as characters ranked by Unicode code point or numbers ranked by value. The whole comparison reduces to one left-to-right pass:

Flowchart loop where a teal box for the next position leads to two decision diamonds, ending in boxes for sequences equal, shorter prefix first, and a yellow box where the smaller element decides.
How the First Differing Element Settles the Order

Programming languages rely on lexicographic order for string comparison and for compound sort keys. Python compares strings, tuples, and lists this way, so sorting tuples shaped like (last_name, first_name) groups people by last name and breaks ties on first name. The same principle explains why ISO 8601 timestamps written in the same format sort chronologically as plain strings.

The element-by-element rule also produces a classic surprise when digits are compared as characters. Because "1" ranks below both "2" and "9", sorting numbered filenames places chapter10.txt ahead of chapter2.txt and chapter9.txt, so chapter ten lands before chapters two and nine. Tools that need human-friendly results extract the digit runs and compare them as integers instead, a scheme known as natural sort order.

How to Use sorted() and sort() in Python

Tutorial

How to Use sorted() and .sort() in Python

In this tutorial, you'll learn how to sort various types of data in different data structures in Python. You'll explore custom sorting orders and work with two distinct ways of sorting.

basics python

For additional information on related topics, take a look at the following resources:


By Martin Breuss • Updated Sept. 6, 2026