Python22 min read

Python Sorting

Learn how sorting works in Python: sort vs sorted, reverse order, key functions, and sorting complex data.

Michael Brown
August 6, 2025
7.5k183

Sorting is a core skill. You will use it for rankings, reports, logs, and UI displays.

    Two main tools:
    - list.sort() → modifies list
    - sorted() → returns new list
    
    ## Basic sorting
    
    ```python
    numbers = [5, 2, 8, 1, 9]
    numbers.sort()
    print(numbers)
    ```
    
    ```python
    numbers = [5, 2, 8, 1, 9]
    new_list = sorted(numbers)
    print(new_list)
    print(numbers)
    ```
    
    ## Reverse order
    
    ```python
    numbers.sort(reverse=True)
    print(numbers)
    ```
    
    ## Custom key sorting
    
    ```python
    words = ["apple", "hi", "banana", "kiwi"]
    words.sort(key=len)
    print(words)
    ```
    
    ```python
    numbers = [-5, 3, -2, 8, -1]
    numbers.sort(key=abs)
    print(numbers)
    ```
    
    ## Sorting complex data
    
    ```python
    students = [
        {"name": "Tom", "grade": 85},
        {"name": "Sarah", "grade": 92},
        {"name": "Mike", "grade": 78}
    ]
    
    students.sort(key=lambda s: s["grade"], reverse=True)
    for s in students:
        print(s)
    ```
    
    ## Multiple keys
    
    ```python
    data = [("Tom", 25), ("Sarah", 25), ("Mike", 30)]
    data.sort(key=lambda x: (x[1], x[0]))
    print(data)
    ```
    
    ## Graph: sorting logic
    
    ```mermaid
    flowchart LR
      A[Original list] --> B[Key function]
      B --> C[Comparison]
      C --> D[Sorted list]
    ```
    
    ## Key points
    
    - sort modifies, sorted returns new
    - Use key for custom logic
    - Stable sorting preserves order
    
    In the next lesson, you will learn pathlib, a modern way to handle file paths and directories.
#Python#Intermediate#Sorting