Python string z-order refers to how strings are sorted and compared when they contain a mix of letters, numbers, and symbols—specifically, the default lexicographic (dictionary) order, not a numeric one. In Python, strings are compared character-by-character using their Unicode code points, so “z” comes after “a”, and “10” comes before “9” because the character ‘1’ (code point 49) is less than ‘9’ (code point 57).
What “z Order” Actually Means in Python
The term “z order” is not a built-in Python feature or function. It usually appears in two contexts: (1) sorting strings alphabetically, where ‘z’ is the last lowercase letter, and (2) the Z-order curve (also called Morton order) used in spatial indexing, which is unrelated to strings. In everyday Python programming, when someone asks about “string z order,” they almost always mean the default sort order of strings—lexicographic order based on Unicode code points. This is the order produced by sorted(), list.sort(), and the comparison operators <, >, <=, >=.
How Python Compares Strings Internally
Python compares strings character by character from left to right. For each position, it compares the Unicode code point (an integer) of the characters. The first difference determines the result. If one string is a prefix of the other, the shorter string is considered smaller. For example:
'apple' < 'banana'→Truebecause ‘a’ (97) < ‘b’ (98)'Zebra' < 'apple'→Truebecause ‘Z’ (90) < ‘a’ (97)'10' < '9'→Truebecause ‘1’ (49) < ‘9’ (57)'abc' < 'abcd'→Truebecause ‘abc’ is a prefix
This behavior is consistent across Python 3.x. Python 2 had a different comparison for mixed types (e.g., strings vs. integers), but that is long gone. The ord() function returns the code point of a single character, and chr() does the reverse.
Sorting Strings: Default vs. Custom Key
To sort a list of strings in default z order, simply call sorted(list_of_strings) or list.sort(). This gives you ascending order (A to Z, then a to z, with uppercase before lowercase). For descending order, use reverse=True. But the default order is often not what humans expect when numbers are involved. For example:
items = ['item10', 'item2', 'item1']
print(sorted(items)) # ['item1', 'item10', 'item2']
Here, ‘item10’ comes before ‘item2’ because ‘1’ is compared before ‘0’ vs ‘2’. To get natural (human) sort order, use a key function that extracts numeric parts. A common approach is to use a regular expression to split the string into numeric and non-numeric chunks:
import re
def natural_key(s):
return [int(part) if part.isdigit() else part.lower() for part in re.split(r'(\d+)', s)]
items = ['item10', 'item2', 'item1']
print(sorted(items, key=natural_key)) # ['item1', 'item2', 'item10']
This works because the key returns a list where numeric parts become integers, so 10 > 2 numerically. For case-insensitive sorting, use key=str.lower.
Common Pitfalls: Case, Accents, and Locale
Three issues trip up beginners and even experienced developers:
- Case sensitivity: Default sort puts all uppercase before lowercase. So ‘Zoo’ < ‘apple’. To sort case-insensitively, use
key=str.lowerorkey=str.casefold(the latter handles more Unicode edge cases). - Accented characters: ‘é’ (233) sorts after ‘z’ (122) in default order. For locale-aware sorting, you need the
localemodule, but it is tricky and platform-dependent. A simpler cross-platform solution is to use a custom key withunicodedata.normalizeto strip accents. - Leading zeros: ’02’ < ‘1’ in default order, which may be surprising. Natural sort handles this correctly if you convert to integers.
A common misconception is that Python sorts by ASCII values. That is close but not exact—Python uses Unicode code points, which for ASCII characters are identical, but for non-ASCII characters, the order is based on the full Unicode table.
Comparing Strings with <, >, ==, and .startswith()
Beyond sorting, z order affects all comparison operators. These are used in conditional logic, binary search, and range checks. For example, checking if a filename is in the ‘a’ to ‘m’ range:
filename = 'log.txt'
if 'a' <= filename < 'n':
print("In first half")
This works because ‘log.txt’ starts with ‘l’ which is between ‘a’ and ‘n’. However, be careful: this is lexicographic, not length-based. Also, str.startswith() and str.endswith() are not comparisons but prefix checks—they are O(n) and do not rely on z order.
Z-Order Curve: The Other Meaning
If you encountered “z order” in a data structure or graphics context, it might refer to the Z-order curve (Morton order), which maps multi-dimensional data to a single integer while preserving locality. This is used in spatial indexes (e.g., in databases or quadtrees). In Python, you might implement it by interleaving the bits of coordinates. This has nothing to do with string sorting, but it is worth knowing because the phrase is ambiguous. For strings, there is no built-in Z-order curve function—you would need to write bit manipulation yourself.
Performance and Memory Considerations
Sorting strings in Python is efficient—TimSort, the default algorithm, runs in O(n log n) worst-case and O(n) on nearly sorted data. Comparing strings is O(k) where k is the length of the common prefix, so very long strings with identical prefixes can be slow. For large datasets, consider storing strings as bytes if they are ASCII, since byte comparison is faster. Also, using key functions that compute derived values once per item (rather than repeatedly inside the comparison) is the right way to optimize. For example, sorted(data, key=str.lower) computes the lowercase version once per item, not per comparison.
Frequently Asked Questions
Why does ’10’ come before ‘2’ when sorting strings?
Because Python compares character by character. The first character of ’10’ is ‘1’ (code point 49), and the first character of ‘2’ is ‘2’ (code point 50). Since 49 < 50, ’10’ is smaller. To get numeric order, convert to integers or use a natural sort key.
How do I sort strings case-insensitively?
Use sorted(my_list, key=str.lower) or key=str.casefold. The latter is more aggressive in Unicode normalization and is recommended for international text. For in-place sorting, use my_list.sort(key=str.casefold).
Does Python sort by ASCII or Unicode?
Python 3 sorts by Unicode code points, which are identical to ASCII for characters U+0000 to U+007F. For characters above that, the order follows the Unicode table, not any locale-specific collation. So ‘ä’ (228) sorts after ‘z’ (122).
Can I sort strings in reverse z order?
Yes, pass reverse=True to sorted() or list.sort(). This reverses the lexicographic order, so ‘z’ comes first, then ‘y’, etc. Note that this also reverses case order (uppercase before lowercase becomes lowercase before uppercase).
What is the fastest way to sort a large list of strings?
Use the built-in sorted() or list.sort()—they are implemented in C and highly optimized. Avoid writing your own comparison function in Python unless absolutely necessary, as it will be much slower. If you need a custom order (e.g., natural sort), precompute a key list and use key=.
Why does ‘Z’ sort before ‘a’?
Because uppercase letters have lower Unicode code points than lowercase letters. ‘Z’ is 90, ‘a’ is 97. So in default ascending order, all uppercase letters come before all lowercase letters. To ignore case, use a casefold key.
Related
- Generate Random Number Range C++: A Practical Guide
- What Is the Shortcut for Save? (Ctrl+S & More)
- Data Entry in Computerized Method: How It Works
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Break-Even Analysis Calculator Excel TemplateA break-even analysis calculator in Excel shows how many units you must sell—or how much sales revenue you…
- Excel Data Model: How to Group Dates in PivotTablesExcel PivotTables built from the Data Model cannot use the ordinary right-click Group command to group dates. Instead,…
- Animated Text in PowerPoint: How to Add and Control ItTo animate text in PowerPoint for Microsoft 365 on Windows, select its text box, open Animations, and choose…
- Excel Circular Reference Warning: Causes and FixesAn Excel circular reference warning means a formula refers to its own cell, either directly or through a…
- Power Query Basics: Import, Clean, and Transform DataPower Query is Excel’s data-import and transformation tool: it connects to files, databases, and other sources, then lets…
- Conditional Formatting Text in Excel: Rules and ExamplesTo conditionally format text in Excel for Microsoft 365 on Windows, select the cells, then choose Home >…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.