Sorting a list of strings in Python is commonly done with sorted(list) or list.sort(). Both accept parameters such as key to customize ordering and reverse to control direction. Strings are compared lexicographically based on Unicode code points, which affects case-sensitive results and ordering of mixed-case data. This guide explains core behavior, parameters, performance, and reliable patterns for predictable string sorting.
Core Functions and Differences
Use sorted(iterable) to return a new sorted list, leaving the original unchanged. Use list.sort() to sort in place and return None. Both accept the same core arguments:
key: function applied to each element before comparisonreverse: set toTruefor descending order
sorted Built-In
sorted(iterable, key=None, reverse=False) returns a new list and works with any iterable. It is stable, so items that compare equal retain their original order.
list Sort Method
list.sort(key=None, reverse=False) modifies the list in place and has slightly lower memory overhead. Choose it when you do not need to keep the original order.
Basic Lexicographic Sort
Without a key, strings are ordered by Unicode code point values. Uppercase letters sort before lowercase, which can yield results such as ["Apple", "banana", "cherry"]. For many use cases this behavior is sufficient, but case-insensitive sorting is often preferred.
Case-Insensitive and Key-Based Sorting
To ignore case, supply key=str.lower (or key=str.casefold for more aggressive Unicode case folding). This keeps the original strings intact while comparing lowercased versions:
sorted(data, key=str.lower)data.sort(key=str.lower)
Prefer str.casefold when working with non-ASCII text that includes characters such as German sharp s (ß).
Locale-Aware Sorting
For natural, locale-sensitive ordering (e.g., treating accented characters appropriately), use Python’s locale module in combination with locale.strxfrm as the key. This requires setting the desired locale with locale.setlocale. On some platforms you can also leverage third-party libraries such as PyICU or the ICU binding for more consistent cross-platform behavior. Below is a compact reference table for locale-related considerations:
| Attribute | Verified Detail | Source Type |
|---|---|---|
| Module | locale | Python Standard Library |
| Key function | locale.strxfrm | Python Standard Library |
| Requirement | locale.setlocale | Platform-dependent configuration |
| Platform note | Behavior may vary across OS locales | Implementation-specific |
Sorting by String Length
To order by length, use key=len. Combine with a secondary sort by passing a tuple from key to achieve deterministic ordering:
sorted(data, key=lambda s: (len(s), s.lower()))
This pattern sorts primarily by length and secondarily by case-insensitive alphabetical order, which improves predictability when lengths are equal.
Numeric and Mixed Data
If your list contains numeric values or mixed types, convert numbers to strings consistently or sort keys that extract the string representation. For purely numeric sorting, applying key=int or key=float is more appropriate. Attempting to compare incompatible types in Python 3 raises a TypeError, so ensure homogeneous or safely comparable data.
Performance Considerations
Both sorted and list.sort use Timsort, with O(n log n) worst-case performance. The key function is called exactly once per element, making it efficient for lightweight transformations. Avoid heavy computation inside key in loops; compute reusable keys if needed. For very large datasets, consider memory usage and whether an in-place sort with list.sort is preferable to sorted allocating a new list.
Reverse Sorting and Stability
Set reverse=True to sort in descending order. Stability ensures that records with equal keys maintain input order, which is valuable when chaining sorts on multiple fields. For example, sorting by department and then by name preserves name order within each department.
Common Patterns and Pitfalls
- Always prefer
key=str.casefoldoverkey=str.lowerfor international text. - Avoid sorting inside loops; compute keys once.
- Use tuples in
keyto implement multi-level sorting. - Be explicit about locale settings; do not rely on default platform behavior.
Summary
Sorting lists of strings in Python is straightforward with sorted() and list.sort(), enhanced by the key and reverse parameters. Choose case-insensitive keys for predictable ordering, consider locale-aware transforms for international text, and apply stable, deterministic patterns for compound sort criteria. These evergreen techniques remain applicable across Python versions and domains.