Sorting Structures
Sort lists of numbers, strings, tuples, and dictionaries correctly using key functions, multiple keys, and stable sorting with real examples.
Sorting is a core operation in data structures. Python provides: - `sorted()` (returns new list) - `list.sort()` (sorts in place) ## Sort numbers ```python nums = [5, 2, 8, 1] print(sorted(nums)) ``` ## Sort strings ```python words = ["banana", "apple", "kiwi"] words.sort() print(words) ``` ## Sort by custom key (very important) Sort by length: ```python words = ["apple", "hi", "banana", "kiwi"] words.sort(key=len) print(words) ``` ## Sort dicts in a list ```python 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: ```python data = [("Tom", 25), ("Sarah", 25), ("Mike", 30)] data.sort(key=lambda x: (x[1], x[0])) print(data) ``` ## Graph: sorting pipeline ```mermaid 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)