Python
Data Structures
Sorting
Lists
Duplicate

Python data structure sort list alphabetically

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Sorting a Python list alphabetically is straightforward with sorted or list.sort, but real world data often includes mixed case, leading spaces, accents, or structured objects. Choosing the right sort strategy keeps results stable and predictable. Understanding key functions is the difference between quick scripts and robust data handling.

sorted Versus list.sort

Python gives two primary options:

  • sorted(iterable) returns a new list
  • list.sort() sorts in place and returns None
python
1names = ["Zoe", "anna", "Mike"]
2
3new_sorted = sorted(names)
4print(new_sorted)  # ['Mike', 'Zoe', 'anna']
5print(names)       # original unchanged
6
7names.sort()
8print(names)       # now changed in place

Use sorted when you need immutability or functional style transformations.

Case Insensitive Alphabetical Sort

Default string comparison is case sensitive. For user facing lists, case insensitive sorting is usually preferred.

python
names = ["Zoe", "anna", "Mike", "bob"]
result = sorted(names, key=str.casefold)
print(result)  # ['anna', 'bob', 'Mike', 'Zoe']

casefold is stronger than lower for Unicode aware text normalization.

Trimming and Normalizing Input

Data from files and forms often includes spaces. Normalize before comparing.

python
raw = ["  Banana", "apple ", "  cherry", "Apple"]
result = sorted(raw, key=lambda s: s.strip().casefold())
print(result)

If you need cleaned output values too, create transformed records rather than sorting dirty data repeatedly.

Sorting Structured Data by Text Field

For lists of dictionaries or objects, set a key function that extracts target field.

python
1users = [
2    {"id": 3, "name": "zoe"},
3    {"id": 1, "name": "Anna"},
4    {"id": 2, "name": "mike"},
5]
6
7users_sorted = sorted(users, key=lambda u: u["name"].casefold())
8print(users_sorted)

You can sort by multiple criteria with tuple keys.

python
users_sorted = sorted(users, key=lambda u: (u["name"].casefold(), u["id"]))

Ascending and Descending

Use reverse=True for descending order.

python
words = ["ant", "bee", "cat"]
print(sorted(words, reverse=True))  # ['cat', 'bee', 'ant']

For complex keys, reverse still applies after key computation.

Locale Aware Sorting

Alphabetical order can vary by language rules. If locale correctness matters, use locale aware tools.

python
1import locale
2
3locale.setlocale(locale.LC_COLLATE, "en_US.UTF-8")
4items = ["ä", "a", "z"]
5result = sorted(items, key=locale.strxfrm)
6print(result)

Locale behavior depends on environment support, so test in deployment context.

Stable Sorting Behavior

Python sort is stable, meaning equal keys keep original relative order. This enables multi pass sorting strategies.

python
1records = [
2    {"name": "alice", "team": "B"},
3    {"name": "alice", "team": "A"},
4]
5
6records.sort(key=lambda r: r["team"])
7records.sort(key=lambda r: r["name"])
8print(records)

Stability is useful when sorting large data with layered business rules.

Performance Notes

Sorting is generally O(n log n). For large lists, avoid recomputing expensive key logic in many repeated sorts. Precompute normalized keys when sorting repeatedly.

python
pairs = [(name.casefold(), name) for name in names]
pairs.sort(key=lambda p: p[0])
result = [orig for _, orig in pairs]

This can reduce overhead in batch data pipelines.

Domain Specific Ordering Rules

Some products require custom ordering that is not pure alphabetical, such as pushing high priority prefixes first or keeping numeric suffixes grouped naturally. In those cases, implement a dedicated key function and document it near the code so future maintainers understand why the order differs from standard lexical sorting.

Common Pitfalls

  • Expecting list.sort() to return a sorted list instead of modifying in place.
  • Forgetting case sensitivity and getting unexpected uppercase first ordering.
  • Sorting dirty strings with leading spaces and assuming user visible order is correct.
  • Ignoring locale requirements for non English alphabetical rules.
  • Re sorting large datasets repeatedly without caching normalization keys.

Summary

  • Use sorted for new lists and list.sort for in place changes.
  • Apply key functions for case insensitive and normalized alphabetical ordering.
  • Use tuple keys or stable sorting for multi criteria ordering.
  • Consider locale aware sorting when language rules matter.
  • Precompute keys for repeated large scale sorting workloads.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

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

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.