Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 46 / PERFORMANCE AND INTERNALS

Sorting and the cost of a choice

Choose sort keys and reason about work as input grows.

IntermediateTutorial 13 min core+10 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners who can read small Python functions and want to apply the listed foundations.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 13 minutes; optional deep dive: 10 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Sort without losing original order
  • Use key functions
  • Distinguish input and auxiliary space
01

Choose in-place versus new output

Sorting chooses an order by keys. sorted makes a new outer list; list.sort changes an existing list and returns None.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Choose a ranking key and an ownership contract before choosing the operation. Python's stable sort keeps input order among equal keys, which matters when tied arrivals should retain their places.

Words you will see

Key function
A function producing the value used to compare each item.
Stable sort
A sort preserving the input order of items whose keys compare equal.
Shallow result
A new outer container that still refers to the same element objects.

Follow the score ranking

The lambda reads row[1], the score. reverse=True puts larger scores first. Lin has 10 and moves ahead of the two eights. Ada remains before Sam because their keys are equal and sorting is stable, even in descending order.

The first print shows the ranking and the second shows the input still in arrival order. sorted allocates an outer result list; it does not recursively copy records. The example uses tuples of strings and integers, so there are no nested mutable fields to edit.

Choose a different rule explicitly

If names must break ties alphabetically, include a secondary key rather than assuming stability invents it. Stability preserves whatever input order existed; an unstable upstream source may still yield variable ties.

Use list.sort when the caller owns the list and wants it rearranged. Do not assign ranked = scores.sort(), because ranked would be None. For bounded key and comparison costs, CPython sorting has O(n log n) worst-case work and may use O(n) temporary storage; in-place is not a constant-memory promise.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. scores = [("Ada", 8), ("Lin", 10), ("Sam", 8)]

    Record arrivals with a deliberate tied score.

  2. ranked = sorted(scores, key=lambda row: row[1], reverse=True)

    Build a descending ranking using only score as the key.

  3. print(ranked)

    Observe Lin first and the stable Ada/Sam tie.

  4. print(scores)

    Observe that the original outer order is unchanged.

list.sort changes a list and returns None. sorted accepts an iterable and returns a new list. Use key to express the value that determines order.

Conceptual stable ranking with a separate outer result

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. KeysRead scores 8, 10 and 8 once per record.
  2. OrderMove score 10 first and preserve Ada before Sam for the equal eights.
  3. OwnershipStore the ranked references in a new list; the original list order remains.
Predict before you run

Why does Ada stay ahead of Sam?

Rank by scorePYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Move a tied arrival.

Try: Swap the Ada and Sam tuples in scores.

Sam now precedes Ada in the tied ranking; Lin is still first.

Observe the in-place return.

Try: Replace the ranked assignment with ranked = scores.sort(key=lambda row: row[1], reverse=True).

ranked prints None and scores prints the rearranged list.

Before you move on

For fresh arrivals [('Zed', 4), ('Ari', 4)], which name comes first under this score-only rule?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

Zed remains first. Equal keys preserve arrival order; an alphabetical tie-breaker would be a changed requirement.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Big-O describes growth

Big-O describes how work grows with input size under a stated cost model, not an exact time or a guarantee that a small run is fast.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Count repeated operations before measuring a clock. A linear scan doubles its checks as n doubles; a loop that repeatedly scans the whole input can grow quadratically.

Words you will see

n
The number of input elements in the cost model.
O(n)
An upper growth bound proportional to n, ignoring constant factors.
Auxiliary space
Additional storage used by an algorithm, beyond the existing input.

Count work that the source actually performs

scan increments once for every input item, so lists of lengths three and six produce counts three and six. This deliberately measures visits, not seconds. Every visit has bounded counter work in the teaching model.

For arbitrary-size Python integers, increment costs depend on the counter's bit length; the usual simple analysis treats those small counters as unit-cost. State such assumptions instead of presenting O(n) as a universal machine-time law.

Compare growth without overclaiming

A nested pair scan would perform n squared visits, while a comparison sort commonly needs O(n log n) comparisons in the worst case. If comparing two long strings costs up to L character checks, include that extra cost rather than silently treating every comparison as constant.

Big-O is an upper bound, not an exact count or average-case claim. An O(n) algorithm can be slower on tiny data because constants differ. Benchmarks and growth reasoning answer different questions; this example demonstrates counts only and makes no speed measurement.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. visits = 0

    Start a local work counter.

  2. for _ in values:

    Visit each supplied item once.

  3. visits += 1

    Count one iteration independently of the item's value.

  4. return visits

    Report a work count, not a clock measurement.

O(1) means independent of the number of items under the stated cost model, not zero time. O(n) scans all items; O(n log n) is a common comparison-sort bound. A fast small example is not enough to establish complexity.

Predict before you run

What does the example measure?

Count visits instead of guessing secondsPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Use empty input.

Try: Replace the first scan argument with [].

The first count is 0 because the loop never enters.

Vary values without varying size.

Try: Replace [1, 2, 3] with [9, 9, 9].

The visit count remains 3. This loop ignores element values.

Before you move on

For a fresh list of 12 items, what count does scan return, and is that 12 milliseconds?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

It returns 12 visits. No timer is used, so no time unit can be attached. A different machine does not change the logical visit count.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

Do not ignore the helper operation

A helper inside a loop can dominate the cost. Repeated list membership scans differ from average-case hash-set lookup.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

When removing repeats but retaining first-arrival order, track output separately from membership state. A set is suitable only when values are hashable and the extra memory is acceptable.

Words you will see

Membership
Testing whether a value is already present.
Hashable
Usable as a hash-table key with stable hashing and equality behaviour.
Collision
Different keys sharing hash-table placement information, possibly increasing lookup work.

Use one structure for order and one for lookup

seen remembers which strings have appeared. output records the first occurrence in arrival order. The second red is already seen, so it is skipped; blue and green are appended once. Displaying output is deterministic and does not depend on set iteration order.

A list-only version using value not in output is simple for small inputs but may scan every accumulated value for each new distinct input. With n distinct values that is quadratic worst-case equality work under bounded-cost comparisons.

State the average and the worst case

With ordinary well-distributed hashes and bounded-cost hash/equality, set membership and insertion take expected average O(1), so this pass takes expected O(n) time and O(u) extra slots for u distinct values. This is not a worst-case constant-time guarantee.

With severe collisions, lookup can require O(u) comparisons and the whole pass can degrade toward O(n squared). Hashing long strings also has its own cost. For unhashable items choose a list scan, a stable key function or another representation; do not silently change equality semantics.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. seen = set()

    Create membership state without treating its iteration as ordered.

  2. if value not in seen:

    Select only the first occurrence under equality.

  3. seen.add(value)

    Remember a selected value before the next iteration.

  4. output.append(value)

    Keep selected values in arrival order in a separate list.

A loop with x in some_list inside may scan that list every time. A set can improve repeated membership at the cost of additional memory. Explain the assumptions and trade-off.

Predict before you run

Which structure determines output order?

Keep order while accelerating ordinary membershipPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Repeat another item.

Try: Append another 'blue' to values.

The output stays unchanged; the original display includes the extra occurrence.

Try an unsupported element.

Try: Replace the first string with [].

Membership raises TypeError for an unhashable list. The example does not hide it.

Before you move on

For fresh input ['b', 'a', 'b', 'a'], what order should output retain?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

['b', 'a']. The set tests membership only; it does not decide the result's order.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Derive the ranking contract before choosing an operation

In the score example, the input order is Ada with 8, Lin with 10, and Sam with 8. Ranking descending by the numeric score moves Lin first. Ada remains ahead of Sam because their keys compare equal and Python sorting is stable. Stability preserves an existing relationship; it does not invent an alphabetical secondary rule or make results deterministic when the original input order itself varies.

Ask whether the caller needs the original sequence afterward. sorted builds a new outer list, so the printed scores retain their original order. list.sort changes the existing list and returns None, making assignment from that return value a contract error. Neither operation recursively copies each record. If records contain mutable fields, changing those fields through the result can still affect objects visible through the original list.

Account for keys, comparisons and temporary storage

For n records, a comparison sort has an O(n log n) worst-case comparison bound under the usual constant-cost comparison model. Python evaluates a key function once per input item for a sort, rather than calling it anew for every comparison. An expensive key can therefore contribute substantial work before comparisons begin. Include string length, decoding, or remote lookup costs if your key computation performs more than bounded local access.

An in-place interface does not imply constant auxiliary memory. CPython sorting can use O(n) temporary space, and sorted also needs its result list. The input objects already exist, so distinguish total retained data from additional storage introduced by ranking. Existing ordered runs can reduce sorting work, but that adaptive behavior does not justify promising the same runtime for random data, reversed data, and a nearly ordered production feed.

Choose an algorithm for the result actually needed

The word-length challenge orders fig before pear, plum, and kiwi. All three four-letter words retain their input relationship. If the requirement changes to length followed by alphabetical order, use a compound key conceptually containing both values. A descending primary score and ascending name need deliberate direction handling; reversing an entire compound ordering also reverses the secondary component, which may violate the new specification.

When only three largest numbers are needed, sorting everything and slicing is clear for a small input. For a very large stream and small fixed k, a bounded heap can retain k candidates in O(k) space with O(n log k) selection work, followed by ordering the selected results. Specify how ties are resolved before replacing the sort. A selection algorithm that drops equal candidates arbitrarily can break the stable result contract.

Build correctness and growth evidence separately

Test empty input, one record, duplicate scores, already ordered records, and repeated references. Assert both the ranking and preservation of the original outer sequence when using sorted. Decide whether missing scores, incompatible types, or non-finite numeric values are rejected before sorting. Otherwise a comparison failure can surface far from the input boundary, and apparently numeric values can produce an ordering the learner never intended.

Benchmark parsing, key calculation, sorting, and formatting as distinct stages before optimizing. Use increasing sizes and representative distributions, repeat measurements, and record the interpreter and environment. Growth analysis explains why repeated list membership inside a loop can dominate a later sort: n scans of up to n elements create quadratic work. Replacing that lookup with a set changes memory use and requires hashable keys, so preserve behavior while measuring the trade.

Transfer question: A leaderboard needs the five highest scores, preserves arrival order for ties, and receives a stream too large to retain. How would you change the design?

Assign each arrival a monotonically increasing position and maintain at most five candidates in a heap ordered so that the least desirable retained candidate can be removed. Desirability combines a higher score with an earlier arrival. After traversal, order those five by descending score and ascending arrival position. This retains O(5) candidates and scans every record; it does not avoid reading the stream. Test six equal scores to prove the earliest five survive, plus empty input and a later strictly higher score. Validate scores before heap insertion and acknowledge that an infinite stream needs a reporting window.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

Does list.sort return the sorted list?
TRANSFER THE IDEA

Sort by length

Order words by length, preserving the original order of ties.

Your practice starterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

MAKE THE RULE WORK ON NEW INPUTS

Guided practice and transfer

These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.

A short function primer before you begin

def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.

return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.

Return a value, do not only print itPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

GUIDED PRACTICE

Preserve arrival order for ties

Rank (name, integer score) tuples descending by score only. Keep equal-score arrivals in their original order and preserve the original list.

The contract

  • Input is a list of (string name, integer score) tuples. Negative scores and repeated records are allowed.
  • Return a fresh outer list sorted descending by score only; ties retain input order.
  • Do not mutate the input or copy its tuple elements. No I/O.
Preserve arrival order for tiesPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Inspect 6 public checks

Transparent local learning checks, not exhaustive or tamper-proof grading.

  1. mixed
    source = [('Ada', 8), ('Lin', 10), ('Sam', 8)]
    before = source.copy()
    result = rank_scores(source)
    assert type(result) is list and result == [('Lin', 10), ('Ada', 8), ('Sam', 8)]
    assert source == before and result is not source
    assert result[0] is source[1] and result[1] is source[0]
  2. empty
    source = []
    before = source.copy()
    result = rank_scores(source)
    assert type(result) is list and result == []
    assert source == before and result is not source
    
  3. tied reverse names
    source = [('Zed', 2), ('Ari', 2)]
    before = source.copy()
    result = rank_scores(source)
    assert type(result) is list and result == [('Zed', 2), ('Ari', 2)]
    assert source == before and result is not source
    assert result[0] is source[0] and result[1] is source[1]
  4. negative
    source = [('a', -3), ('b', -1), ('c', 0)]
    before = source.copy()
    result = rank_scores(source)
    assert type(result) is list and result == [('c', 0), ('b', -1), ('a', -3)]
    assert source == before and result is not source
    
  5. repeated identity
    item = ('a', 1)
    source = [item, item]
    result = rank_scores(source)
    assert type(result) is list and result == [item, item] and result is not source
    assert result[0] is result[1] is item and source == [item, item]
  6. independent outer
    source = [('a', 1)]
    before = source.copy()
    result = rank_scores(source)
    assert type(result) is list and result == [('a', 1)]
    assert source == before and result is not source
    result.clear()
    assert source == [('a', 1)]
    Does sorted deep-copy records?

    No. It allocates a fresh outer list of existing references. CPython uses O(n log n) worst-case time under constant-cost score comparisons, may adapt to O(n) for ordered runs, and may use O(n) temporary storage plus the result.

    GUIDED PRACTICE

    Separate membership from output order

    Return each integer once in first-occurrence order, without changing the source. Keep a membership set separate from the result list.

    The contract

    • Input is a list of integers; preserve first-occurrence order, including negative values and zero.
    • Return a fresh list, removing later equal occurrences only; input is unchanged.
    • Use no sorting or I/O. A set may support membership but must not supply result iteration order.
    Separate membership from output orderPYTHON 3

    Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

    Preparing the editor controls. Run and editing become available when this page is interactive.

    Browser Python limits

    Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

    Inspect 6 public checks

    Transparent local learning checks, not exhaustive or tamper-proof grading.

    1. order
      source = [3, 1, 3, 2, 1]
      before = source.copy()
      result = first_occurrences(source)
      assert type(result) is list and result == [3, 1, 2]
      assert source == before and result is not source
      
    2. empty
      source = []
      before = source.copy()
      result = first_occurrences(source)
      assert type(result) is list and result == []
      assert source == before and result is not source
      
    3. all repeats
      source = [7, 7, 7]
      before = source.copy()
      result = first_occurrences(source)
      assert type(result) is list and result == [7]
      assert source == before and result is not source
      
    4. negative zero
      source = [0, -2, 0, -1, -2]
      before = source.copy()
      result = first_occurrences(source)
      assert type(result) is list and result == [0, -2, -1]
      assert source == before and result is not source
      
    5. already distinct
      source = [9, 3, 1]
      before = source.copy()
      result = first_occurrences(source)
      assert type(result) is list and result == [9, 3, 1]
      assert source == before and result is not source
      
    6. new outer
      source = [4]
      before = source.copy()
      result = first_occurrences(source)
      assert type(result) is list and result == [4]
      assert source == before and result is not source
      result.append(9)
      assert source == [4]
      Is set membership worst-case constant time?

      No. Under ordinary bounded hash/equality and well-distributed hashes this pass is expected O(n), with O(u) storage for u distinct values. Collisions can make individual lookups O(u) and the pass approach O(n squared).

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: change the tie rule

      The ranking rule changes: descending score, then ascending case-sensitive name. Retain arrival order only when both keys are equal, and preserve the source.

      The contract

      • Input is a list of (string name, integer score) tuples. Integers can be negative and duplicates remain.
      • Return a fresh outer list ordered by descending score and ascending case-sensitive Unicode string name.
      • When both key components equal, preserve arrival order. Reuse tuple elements, do not edit the source. No I/O.
      Transfer: change the tie rulePYTHON 3

      Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

      Preparing the editor controls. Run and editing become available when this page is interactive.

      Browser Python limits

      Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

      Inspect 6 public checks

      Transparent local learning checks, not exhaustive or tamper-proof grading.

      1. changed tie
        source = [('Zed', 8), ('Ari', 8), ('Lin', 10)]
        before = source.copy()
        result = rank_named(source)
        assert type(result) is list and result == [('Lin', 10), ('Ari', 8), ('Zed', 8)]
        assert source == before and result is not source
        assert result[0] is source[2] and result[1] is source[1]
      2. empty
        source = []
        before = source.copy()
        result = rank_named(source)
        assert type(result) is list and result == []
        assert source == before and result is not source
        
      3. negative scores
        source = [('b', -2), ('a', -2), ('z', -1)]
        before = source.copy()
        result = rank_named(source)
        assert type(result) is list and result == [('z', -1), ('a', -2), ('b', -2)]
        assert source == before and result is not source
        
      4. case sensitive
        source = [('a', 1), ('Z', 1), ('A', 1)]
        before = source.copy()
        result = rank_named(source)
        assert type(result) is list and result == [('A', 1), ('Z', 1), ('a', 1)]
        assert source == before and result is not source
        
      5. equal keys stable identity
        left = tuple(['x', 2])
        right = tuple(['x', 2])
        source = [left, right]
        result = rank_named(source)
        assert type(result) is list and result == [('x', 2), ('x', 2)] and result is not source
        assert result[0] is left and result[1] is right and source[0] is left and source[1] is right
      6. different primaries
        source = [('a', 0), ('z', 3), ('b', 1)]
        before = source.copy()
        result = rank_named(source)
        assert type(result) is list and result == [('z', 3), ('b', 1), ('a', 0)]
        assert source == before and result is not source
        
        Why not reverse the entire tuple key?

        That also makes the name descending. Worst-case comparisons are O(n log n) in CPython; with bounded integer operations and names up to L characters, a conservative time bound includes O(L) tie comparisons. Storage is O(n) result and temporary slots, plus key objects.

        A GOOD PLACE TO PAUSE

        Core route complete.

        If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.

        Save your core reading milestone

        Sort adapts to existing order

        CPython's stable adaptive sort uses existing ordered runs. Its in-place interface does not imply constant auxiliary memory.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Separate language behaviour, such as stability, from implementation details, such as CPython's adaptive algorithm. Define key and comparison costs before quoting time bounds.

        Words you will see

        Run
        A consecutive part of the input already ordered in a useful direction.
        Adaptive
        Able to take advantage of structure already present in the input.
        Worst case
        The most work among permitted inputs of a specified size under a chosen model.

        Observe keys, not a fictional timing trace

        key appends one marker for each element it is asked to rank. Sorting four integers prints an ordered result and a key-call count of four. Python computes each key once for the sort; it does not rerun this key for every comparison.

        The list.sort return is None, so values itself is read after the call. The observations do not reveal internal merges or peak memory. A conceptual model of runs must not be presented as an instrumented trace from this counter.

        Scope the complexity statement

        For CPython with bounded-cost keys and comparisons, worst-case sorting time is O(n log n), while already ordered runs can yield O(n) best-case work. A usual random-permutation comparison model also gives O(n log n) expected time; there is no universal average without an input distribution.

        Temporary storage can be O(n), including key-related storage when keys are supplied. sorted additionally allocates an n-slot result list. Expensive keys contribute their total computation cost, and expensive comparisons contribute per-comparison work. In-place describes which list is rearranged, not the memory bound.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. calls.append(1)

          Record one key evaluation without timing it.

        2. return value

          Rank by the integer itself.

        3. result = values.sort(key=key)

          Rearrange the existing list and retain its None return for inspection.

        4. print(len(calls))

          Count four key calls, not comparison operations.

        CPython uses an adaptive stable sorting algorithm that benefits from existing runs. Worst-case time is O(n log n); temporary space can be O(n). sorted also allocates the result list. Do not call all in-place algorithms O(1) auxiliary space.

        Predict before you run

        Does the key-call count measure comparisons?

        Count key evaluation, not elapsed timePYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Try ordered input.

        Try: Set values = [1, 1, 2, 3].

        The key count stays 4; this does not establish identical comparison work.

        Preserve the outer input instead.

        Try: Use result = sorted(values, key=key) and print(result) before print(values).

        The returned list is ordered while values retains its input order, with four key calls.

        Before you move on

        If a fresh input has ten items already ordered, how many times does this key run?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        Ten, once per item. Adaptation can reduce ordering work but does not eliminate the need to obtain each supplied key.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Measure the right thing

        A benchmark needs a defined workload and measurement boundary. A deterministic work counter teaches scaling without pretending to be a wall-clock benchmark.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Before optimising, separate parsing, key calculation, sorting and formatting. Confirm equivalent outputs so an incorrect shortcut is not celebrated as faster.

        Words you will see

        Workload
        The size and distribution of inputs used for a measurement.
        Measurement boundary
        Which stages are included in a reported metric.
        Baseline
        A known-correct version used for comparison.

        Isolate an expensive helper

        visits counts how many items the deliberately repeated membership model inspects. For each value it scans the whole list until it finds that value. With distinct ordered input, finding positions one through n takes 1 + 2 + ... + n visits.

        For n equal to 3 the count is 6; for n equal to 6 it is 21. Doubling input nearly quadruples this work. Repeated values would be found earlier, so input distribution changes the count even with the same size.

        Measure performance without changing the promise

        This counter is deterministic logical evidence, not seconds and not a microbenchmark. Real timing should use a monotonic timer, repeated representative workloads and a recorded Python version and machine. Keep setup outside the boundary only when the intended metric excludes setup.

        A set-based replacement trades storage and hashability requirements for better expected lookup. First test identical output, order and duplication rules. Then compare parsing, allocation, computation and output separately; otherwise an unrelated printing or startup cost can hide the actual difference.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. for target in values:

          Repeat one membership-style scan per input item.

        2. for candidate in values:

          Start each search from the front.

        3. if candidate == target:

          Stop at the first matching value.

        4. print(visits([0, 1, 2, 3, 4, 5]))

          Sum scan lengths one through six to get 21 visits.

        Separate parsing, allocation, sorting and output in a benchmark. Repeat measurements on representative inputs. Wall-clock time includes system noise; performance claims need version, workload and environment context.

        Predict before you run

        Why is six-item work 21 rather than 6?

        Expose repeated scans with a work counterPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Change the distribution.

        Try: Replace the six-item list with [0, 0, 0, 0, 0, 0].

        Its count becomes 6 because every search stops immediately.

        Increase distinct input size.

        Try: Replace the first input with [0, 1, 2, 3].

        The first count becomes 10, the sum of one through four.

        Before you move on

        For a fresh list [7, 7, 7, 7], what count does visits produce?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        Four. Every target matches the first candidate. This best-shaped repeated input does not disprove quadratic worst-case work for distinct values.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Make the explanation your own.

        Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.

        Take a versioned study copy

        Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.

        Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.

        REFLECT, THEN CONTINUE

        Make this a milestone.

        Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.

        Your account

        Loading account...

        Sign in to save your work across devices.