ML Foundations

Python sorted orders numbered filenames as text

Plain sorted() compares filename strings lexicographically. Use a numeric key when a number in the name should control order.

Example results for Python sorted orders numbered filenames as text. lexical: 'part-1.txt', 'part-10.txt', 'part-2.txt'
Illustration: Original illustration by Tensor Almanac
Evidence and testing

Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.

Default string order compares characters

`sorted()` returns a new list in ascending order. For strings, that means character ordering, not interpreting digits embedded in a name as a number. So `part-10.txt` comes before `part-2.txt`: after the shared prefix, character `1` sorts before character `2`. [1]

This can surprise a pipeline that processes numbered shards, checkpoint files, or exported records. If order affects concatenation or training input, make the desired ordering rule explicit instead of relying on the directory enumeration or a lexical sort. The example shows both orders using the same three filenames. [1, 2]

References: [1], [2]

Extract the number as a sorting key

Pass `key=` a function that returns the value to compare. The example removes the known prefix and suffix, converts the remaining text to an integer, and sorts by that integer. The files then appear in the expected sequence: 1, 2, 10. [2]

Use a parser that matches your naming convention. If filenames have multiple numeric fields, return a tuple such as `(epoch, shard)`; if names are not guaranteed to match the pattern, validate them before conversion. This sample handles only the exact `part-N.txt` format and intentionally lets malformed names fail rather than silently guessing. [2]

Executed with Python 3.12.14, standard library only; assertions passed.

"""Contrast lexical and numeric ordering for numbered filenames."""
parts = ["part-10.txt", "part-2.txt", "part-1.txt"]

lexical = sorted(parts)
numeric = sorted(
    parts,
    key=lambda name: int(name.removeprefix("part-").removesuffix(".txt")),
)

print("lexical:", lexical)
print("numeric:", numeric)
assert lexical == ["part-1.txt", "part-10.txt", "part-2.txt"]
assert numeric == ["part-1.txt", "part-2.txt", "part-10.txt"]

Recorded output

lexical: ['part-1.txt', 'part-10.txt', 'part-2.txt']
numeric: ['part-1.txt', 'part-2.txt', 'part-10.txt']

References: [2]

Choose text or numeric order deliberately

Lexical order is correct for strings and can be useful when names are designed to sort as text. Numeric order is a separate application rule. Keep the original strings and provide a key when you need to preserve the names while comparing their embedded values. [1, 2]

This example sorts a short in-memory list. It does not read a directory, assume a filesystem’s enumeration order, benchmark sorting, or handle locale-aware text. If file paths come from `Path.glob()`, first collect the matches and sort by a parsed key when numeric sequence order is required. [2]

References: [1], [2]

Sources

  1. Python sorted() built-in
  2. Python Sorting HOWTO: key functions