HOWTO · Python
Lexicographical Order in Python
Learn how Python compares strings lexicographically and sorts strings, words, characters, numbers, and tuples.
On this page
In Python, lexicographic order compares strings from left to right by Unicode code point; the first differing character decides the order, and a shorter prefix comes first. Use sort() to reorder a list in place, sorted() to create an ordered result, and a key function when you need a different comparison rule.
What Lexicographic Order Means in Python
Lexicographic order compares items from left to right. At the first position where two items differ, the item with the smaller value comes first; if one item is a prefix of the other, the shorter item comes first. Python compares strings by Unicode code point, so string ordering is case-sensitive and can differ from a reader’s locale-specific alphabetic expectations. For case-insensitive ordering, choose an explicit key such as str.casefold.
Sort Strings and Words Lexicographically
Use list.sort() to rearrange a list in place. It returns None; use sorted() when you need a new list and want to keep the original iterable unchanged. With no key, Python compares strings character by character.
Run this example:
names = ["pear", "apple", "orange"]
names.sort()
print(names)
['apple', 'orange', 'pear']
The optional key parameter lets you define the value used for comparison. For example, sorted(names, key=str.casefold) sorts without distinguishing uppercase and lowercase. It does not change the stored strings.
To sort the words in a sentence, split it into a list first:
sentence = "pear apple orange"
words = sentence.split()
words.sort()
print(words)
['apple', 'orange', 'pear']
split() separates on runs of whitespace by default. Sorting these words returns an ordered list; it does not preserve punctuation as separate tokens or rebuild the sentence with its original spacing. If those details matter, tokenize and format the text according to the needed rules.
Sort Characters in a String
A string is immutable, so sort its characters with sorted() and join the resulting list to create another string:
word = "delftstack"
ordered_word = "".join(sorted(word))
print(ordered_word)
acdefklstt
The result follows code point order, not a language-aware alphabetization rule. Repeated characters remain repeated. If the intended task is case-insensitive, pass a key to sorted(); if the result must preserve a particular language’s collation rules, use a collation library rather than assuming code point order matches that language.
Sort Numbers by Numeric Value, Not Lexicographic Order
Python compares integers by numeric value. Thus 2 comes before 10; converting those values to strings changes the comparison to character-by-character ordering, where "10" comes before "2".
numbers = [1, 4, 5, 3, 10, 16, 12]
original = numbers.copy()
numbers.sort()
new_numbers = sorted(original)
print(numbers)
print(new_numbers)
print(original)
[1, 3, 4, 5, 10, 12, 16]
[1, 3, 4, 5, 10, 12, 16]
[1, 4, 5, 3, 10, 16, 12]
Both sorting calls above produce a numerically ascending list. sort() changes its list, while sorted() returns a separate list. For numeric strings that should be ordered by value, convert them to numbers in the key, such as sorted(values, key=int), while retaining the original strings if their formatting matters.
Sort Tuples by a Selected Field
Tuples sort lexicographically across their fields by default: Python compares the first fields, then later fields when earlier fields tie. To make one field the primary criterion, pass a key function. itemgetter(1) selects the second field (index 1):
from operator import itemgetter
produce = [(1, "pear"), (3, "orange"), (2, "banana")]
by_name = sorted(produce, key=itemgetter(1))
print(by_name)
[(2, 'banana'), (3, 'orange'), (1, 'pear')]
The selected field controls the primary ordering, while each complete tuple stays together. A key function can also return a tuple when you need multiple criteria, for example (record[1].casefold(), record[0]) to sort by a case-insensitive name and then by an identifier. Use sort() for an in-place update or sorted() when the source order must remain available.