Lexicographic and Numeric Order

Text order compares sequence elements from the start. Numeric order compares magnitudes after the values have been parsed.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Read the first difference
  2. Check a date format
  3. Follow a comparison through repeated prefixes
  4. Choose a test that reveals the intended order

Read the first difference

The string "100" precedes "23" in Python's ordinary string order because the first character 1 precedes 2. Parsing yields numbers 100 and 23 in the opposite order. Their types decide which comparison the program performs.

Check a date format

Consistently zero-padded year-month-day strings such as 2026-02-09 and 2026-11-01 order by calendar date for this fixed year representation. Text spelled February 9 orders alphabetically. A parsing and formatting boundary lets the program store dates as dates and render them in a chosen locale.[1][2]

Follow a comparison through repeated prefixes

Text sorting compares the first differing position under the chosen character or collation rules. In ordinary Python string order, labels "part12" and "part2" agree until the first digit. One comes before two, so part12 appears earlier. To sort by the quantity named in each label, extract a numeric suffix and compare twelve with two. This changes the key, even though the displayed labels remain the same. Key functions make the selection explicit.

Choose a test that reveals the intended order

A list containing only "1", "2", and "3" sorts the same under both simple models. Include "2" and "11" to see the difference. Also include repeated quantities with distinct labels if tie order matters. A stable order can preserve source order or use a documented second key. If labels use uppercase, accents, or punctuation, the application's text rule may include normalization or locale-aware collation. Try a representation with visible formatting and one numeric fixture, and write their expected orders separately. See stable ordering for preserving tie behavior across changes.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩
  2. Python Software Foundation, Python Language Reference: Expressions ↩