Python Tutorial 0/52 lessons ~6 min read Lesson 23

    Sorting

    Python uses Timsort — O(n log n) worst case, O(n) on partially sorted data.

    Course progress0%
    Focus
    8 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Python uses Timsort — O(n log n) worst case, O(n) on partially sorted data. sorted() returns a new list; list.sort() mutates.

    Understanding the topic

    Core concepts to understand:

    • sorted(xs) returns a new list.
    • xs.sort() mutates in place.
    • key= defines sort order.
    • reverse=True for descending.

    Syntax reference

    Visual flow / code:

    python
    nums = [3, 1, 4, 1, 5, 9]
    sorted(nums) # [1,1,3,4,5,9]
    sorted(nums, reverse=True) # [9,5,4,3,1,1]
    # Sort by key
    words = ["banana", "apple", "cherry"]
    sorted(words, key=len) # by length
    # Stable sort by multiple keys
    people = [{"age": 30, "name": "B"}, {"age": 30, "name": "A"}]
    sorted(people, key=lambda p: (p["age"], p["name"]))

    Execution workflow

    1Sorting Workflow
    1 / 4

    sorted(xs) returns a new list

    sorted(xs) returns a new list.

    Real-world use

    Timsort is the gold standard — Java 7+ uses it too. The key function is more efficient than cmp (removed in Py3).

    Best practices

    • Use key over comparison functions.
    • Sort is stable — exploit it for multi-level sort.
    • sorted for safety; .sort() for memory.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1IntermediateQuestionTimsort time complexity?+

    Answer

    Timsort runs in O(n log n) in the worst and average case and O(n) on already sorted or nearly sorted data, because it detects existing runs and merges them. It uses O(n) extra space in the worst case. It is a hybrid of merge sort and insertion sort designed for real-world data.

    Follow-up

    Why is it fast on partially sorted data?
    2IntermediateQuestionIs Python sort stable?+

    Answer

    Yes. Python's sort is guaranteed stable, so items that compare equal keep their original relative order. This lets you sort by multiple keys in passes, sorting by the secondary key first, then the primary key. The guarantee applies to both sorted() and list.sort(), including with reverse=True.

    Follow-up

    How would you sort by two keys using stability?
    3BeginnerQuestionsorted vs .sort()?+

    Answer

    sorted(iterable) accepts any iterable and returns a new sorted list, leaving the original unchanged. list.sort() sorts a list in place and returns None, avoiding a copy. Both accept key and reverse, and a common bug is writing xs = xs.sort(), which sets xs to None.

    Summary

    In summary: Timsort O(n log n), stable. key= is the idiomatic API.

    Ready to mark this lesson complete?Track your journey across the entire course.