programming

How to Sort a List of Strings in Python

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...

Mara Ellison
How to Sort a List of Strings in Python

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 comparison
  • reverse: set to True for 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:

AttributeVerified DetailSource Type
ModulelocalePython Standard Library
Key functionlocale.strxfrmPython Standard Library
Requirementlocale.setlocalePlatform-dependent configuration
Platform noteBehavior may vary across OS localesImplementation-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.casefold over key=str.lower for international text.
  • Avoid sorting inside loops; compute keys once.
  • Use tuples in key to 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.

Related Reading

More pages in this topic cluster.

How to Format a Float to 2 Decimal Places in Python

When you format a float to two decimal places in Python, you are controlling how a floating-point number is presented as text, not how it is stored. This article explains the mo...

Read next
How to Round in Python to 2 Decimal Places: Clear, Verified Approaches

To round in Python to 2 decimal places, the most direct options are round(number, 2) , formatted strings like f'{number:.2f}' or '{:.2f}'.format(number) , and the Decimal type w...

Read next
Is a String a Primitive Data Type in Java?

In Java, a string is not a primitive data type; it is an object of the java.lang.String class. Primitive types in Java are predefined, non-object types such as int , char , bool...

Read next