Data Structures20 min read
Sorting Structures
Sort lists of numbers, strings, tuples, and dictionaries correctly using key functions, multiple keys, and stable sorting with real examples.
David Miller
September 29, 2025
7.2k285
Sorting is a core operation in data structures.
Python provides:
sorted()(returns new list)list.sort()(sorts in place)
Sort numbers
nums = [5, 2, 8, 1]
print(sorted(nums))
Sort strings
words = ["banana", "apple", "kiwi"]
words.sort()
print(words)
Sort by custom key (very important)
Sort by length:
words = ["apple", "hi", "banana", "kiwi"]
words.sort(key=len)
print(words)
Sort dicts in a list
students = [
{"name": "Tom", "grade": 85},
{"name": "Sarah", "grade": 92},
{"name": "Mike", "grade": 78},
]
students.sort(key=lambda s: s["grade"], reverse=True)
print(students)
Multiple keys
Sort by grade then name:
data = [("Tom", 25), ("Sarah", 25), ("Mike", 30)]
data.sort(key=lambda x: (x[1], x[0]))
print(data)
Graph: sorting pipeline
flowchart LR
A[Unsorted list] --> B[key function]
B --> C[Order by key]
C --> D[Sorted list]
Remember
- sorted() makes a new list, sort() changes existing list
- key= is the power tool
- Python sorting is stable (keeps relative order when keys tie)
#Python#Intermediate#Sorting