Python Programming
glob Module
File Handling
Code Order
Python Tips

How are glob.glob's return values ordered?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

glob.glob() returns all matching paths, but you should not rely on the result having a meaningful implicit order. If order matters, the correct fix is to sort the paths yourself instead of depending on whatever order the filesystem happens to produce.

Treat the Raw Result as Unspecified

A small example looks like this:

python
1import glob
2
3paths = glob.glob("data/*.csv")
4print(paths)

That list may look alphabetical on one system and different on another. The Python API does not promise alphabetical, chronological, or stable ordering across machines.

Sort Explicitly When Order Matters

If you want alphabetical order, say so directly:

python
1import glob
2
3paths = sorted(glob.glob("data/*.csv"))
4for path in paths:
5    print(path)

If you want another rule, provide a custom sort key:

python
1import glob
2import os
3
4paths = sorted(glob.glob("data/*.csv"), key=os.path.getmtime)

That example sorts by modification time instead of by filename.

The Same Advice Applies to iglob()

glob.iglob() yields an iterator rather than returning a full list, but the ordering warning is the same:

python
1import glob
2
3paths = sorted(glob.iglob("data/*.csv"))
4print(paths)

If deterministic output matters, make that requirement explicit regardless of which glob function you call.

Choose the Right Sort Rule

A subtle point is that "sorted" is not always the same as "correct". Lexicographic sorting places "file10.txt" before "file2.txt". If your filenames contain numbers and you want natural numeric order, you need a custom key that extracts the numeric part.

So the real question is not just whether you should sort, but what ordering actually matches the application’s logic.

Example of a Natural Sort Key

For filenames with numeric suffixes, a custom key is often better than plain lexicographic sorting:

python
1import glob
2import re
3
4def numeric_key(path):
5    match = re.search(r"(\d+)", path)
6    return int(match.group(1)) if match else -1
7
8paths = sorted(glob.glob("file*.txt"), key=numeric_key)
9print(paths)

This avoids the common "file10" versus "file2" ordering surprise.

Be Explicit in Tests and Pipelines

If production code or tests process files discovered with glob patterns, sort them before asserting on output order:

python
paths = sorted(glob.glob("fixtures/*.txt"))
assert paths[0].endswith("file1.txt")

This makes tests deterministic and prevents false failures caused by incidental filesystem ordering.

The same idea applies to batch jobs. If downstream logic depends on processing "the first file" or "the latest file", encode that rule explicitly instead of hoping raw glob order happens to match it.

Being explicit also makes code review easier. A reader can see immediately whether the intended order is alphabetical, numeric, or time-based instead of having to guess from filesystem behavior.

That clarity is usually worth more than the one extra line of sorting code.

Common Pitfalls

The biggest mistake is observing that glob.glob() appears sorted in one environment and treating that as a guarantee. It is safer to assume nothing about the raw order.

Another common issue is sorting alphabetically when the real requirement was newest-first, oldest-first, or some business-specific sequence.

People also forget that recursive globs across subdirectories make hidden ordering assumptions even more fragile.

Finally, tests that depend on implicit glob order tend to become flaky after unrelated filesystem changes or when run on a different platform.

Summary

  • 'glob.glob() does not provide a reliable semantic ordering you should depend on.'
  • Use sorted(...) or a custom sort key whenever order matters.
  • Apply the same rule to glob.iglob().
  • Decide whether you need alphabetical, time-based, numeric, or another ordering rule.
  • Make ordering explicit so the behavior stays consistent across systems.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.