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 54 / SCENARIO-BASED QUESTIONS

Scenario: a function remembers an earlier request

A helper defined as add(value, items=[]) returns entries from an earlier call even though the second caller supplied only one value. The state survives across calls in one process and disappears after a restart.

FoundationScenario 18 min core+12 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 building Python foundations; revisit the preparation topics whenever the vocabulary is unfamiliar.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 18 minutes; optional deep dive: 12 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
  • Build a diagnosis from evidence
  • Compare a repair with its trade-offs
  • Test the changed behaviour
DIAGNOSTIC CASE FILE

Follow the evidence.

A helper defined as add(value, items=[]) returns entries from an earlier call even though the second caller supplied only one value. The state survives across calls in one process and disappears after a restart.

Observed evidence

  • The default object identity stays the same across calls.
  • Passing an explicit fresh list avoids the observed sharing.
  • The function mutates its parameter with append.

Investigation sequence

  1. Call the helper twice in a clean process.
  2. Inspect whether the shared state comes from a default, global, closure or cache.
  3. Decide whether caller-supplied lists should be mutated or copied.

Challenge the repair

  • Test both omitted defaults and an explicitly supplied empty list.
  • How would you distinguish an omitted value from an explicit None when both are meaningful?
01

Read the incident, not just the error

A default value can remain attached to a function across calls. If that value is a mutable list, later calls can observe changes made by earlier callers.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A helper that unexpectedly returns another request's entries can leak state between callers. Restarting the process may hide the symptom without fixing the lifetime error.

Words you will see

Default argument
A value used when a caller omits an argument.
Definition time
When execution reaches def and creates the function, including evaluating its default expressions.
Call time
When the function body executes for a particular invocation.

Reproduce two calls in the same lifetime

The bad helper appends to items=[], which was created when def ran. The first call uses that list and adds first. The second omitted-argument call uses the same list and adds second. The output shows state surviving across calls without any global variable in the function body.

A fresh process or a newly executed def statement creates a fresh default, so a test that calls the function only once after each redefinition misses the problem. A useful reproduction makes at least two calls through the same function object.

A symptom is not yet a complete API contract

The suspicious part is shared omitted state. It is a separate question whether a list supplied explicitly by a caller should be mutated. Do not repair one policy by silently changing the other. Decide whether the function is an append-to-container operation or a return-new-container operation.

Defaults are ordinary Python values held by the function, not an instruction to rerun their expression on every call. Immutable defaults can be appropriate, but a mutable default should be used only when persistent shared state is intentional and clearly documented.

The original example, step by step

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

  1. def add(value, items=[]):

    Create one list default when this definition executes.

  2. items.append(value)

    Change the selected list rather than creating a new one.

  3. print(add('first'))

    Use the default and append first.

  4. print(add('second'))

    Reuse that changed default and append second.

A helper defined as add(value, items=[]) returns entries from an earlier call even though the second caller supplied only one value. The state survives across calls in one process and disappears after a restart.

Definition lifetime versus call lifetime

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

  1. Definedef creates function F and one default list L.
  2. Call oneOmitted items selects L, then appends first.
  3. Call twoOmitted items selects the same L, already holding first.
Predict before you run

What appears in the second result?

Observe state across omitted argumentsPYTHON 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.

Re-execute the definition before the second call.

Try: Define add again with the same source between the prints.

That creates a different default and masks the cross-call symptom rather than explaining a durable fix.

Supply a list explicitly.

Try: Call add('second', []) for the second print.

That call uses the supplied fresh list, not the retained default.

Before you move on

Why does a one-call test in a fresh process fail to expose this defect?

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

The first call sees a newly created default, so it can look correct. The defect appears when the same function's default is reused after mutation by a previous call.

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

Investigate before changing code

Inspect both the source of state and the ownership promise before choosing a repair. A default, global, closure and explicit input can all retain mutable state for different reasons.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A reliable investigation should identify why the object survives, not simply replace every list with a copy and hope no behavior changes.

Words you will see

Retained state
Data still reachable after one call finishes.
Default tuple
A function's __defaults__ contains its positional default values.
Ownership promise
Which caller is allowed to observe or perform edits to an object.

Use identity and repeated behavior as evidence

Keep both return values from two calls. If first is second, both names reach the same list. Also inspect whether the function retains a default object. This connects the observation to a particular lifetime rather than guessing that Python is caching every list.

Be careful when printing after both calls: the first result may now show entries added by the second call. A returned reference is not automatically a frozen snapshot. Record when a value was observed as part of the reproduction.

Choose the intended behavior of explicit input

If the API's purpose is appending to a supplied list, preserving that mutation may be correct. If the caller expects a new list, the function needs a copy even when the argument was supplied. Using None for omitted state alone does not grant privacy to explicit input.

Keep regression checks for omitted calls, explicit empty input, repeated calls and mutation/identity. A truthiness test such as if not items conflates an explicit empty list with absence and can violate the append-to-supplied-list 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. first = add('a')

    Keep a name for the returned default list.

  2. second = add('b')

    The next call edits that same list.

  3. print(first is second)

    Confirm shared identity rather than merely equal contents.

  4. print(add.__defaults__[0] is first)

    Connect the result to the object retained as the positional default.

Call the helper twice in a clean process. Inspect whether the shared state comes from a default, global, closure or cache. Decide whether caller-supplied lists should be mutated or copied.

Predict before you run

After the second call, what does first contain?

A returned reference is not a snapshotPYTHON 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.

Observe earlier rather than later.

Try: Print first before the second call and again after it.

The earlier display has only a; the later display also has b.

Test explicit empty ownership.

Try: Pass an empty list and check whether the returned object is that exact list.

This distinguishes an in-place contract from a return-new-list contract.

Before you move on

If an explicit empty list is passed to an append-in-place API, may the implementation replace it just because it is false in a condition?

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

Not under that API's ownership promise. It must append to that supplied list. Use is None to distinguish omission from an explicitly supplied empty list.

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

A repair you can explain

Use a sentinel for omission and construct mutable default state inside the call. None is often a useful sentinel when None itself is not a valid supplied collection.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

The function can then give each omitted call its own list while still deliberately editing a caller-supplied list when that is the declared behavior.

Words you will see

Sentinel
A distinguished value that represents a special state such as omission.
is None
An identity test for the one None object, not a general emptiness test.
Fresh per call
Constructed separately during each applicable function invocation.

Move construction to the right lifetime

The repaired definition retains None, not a list, as the default. When items is None, the body creates []. That statement runs separately for each omitted call. Appending then changes the new list owned by that call.

For an explicit list, the condition is false and no replacement occurs. The original source intentionally keeps this supplied-list mutation behavior. The repair addresses accidental default sharing without pretending that every input is now protected from editing.

Know when None is not enough

If a future API allows None as a meaningful explicit input distinct from omission, it needs a separate sentinel such as a private object. Do not automatically adopt that extra machinery when the simpler contract only accepts lists or omission.

Test the behavior you promise: independent omitted calls, correct appended values, deliberate explicit ownership and no state leaking after a later call. A no-error run or one correct printed list is weaker than those contract checks.

The original example, step by step

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

  1. def add(value, items=None):

    Store the immutable omission marker as the default.

  2. if items is None:

    Distinguish omitted state from an explicit empty list.

  3. items = []

    Create a separate list during this call.

  4. print(add('second'))

    The next omitted call starts with another empty list.

None distinguishes an omitted collection from an explicit list. Creating a list inside the function gives independent default state while retaining deliberate caller-supplied mutation.

Predict before you run

Why does the second omitted call not contain first?

Create defaults at call 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.

Verify explicit mutation.

Try: Create supplied = [] and call add('x', supplied), then print(supplied).

The supplied list becomes ['x'], as this in-place contract intends.

Expose the false-empty shortcut.

Try: Replace if items is None with if not items, then test an explicit empty supplied list.

The value result can look correct while the caller's original empty list is no longer the edited object.

Before you move on

After this repair, would add('x', supplied) still change supplied?

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

Yes. If supplied is a list, the sentinel branch does not run. The append edits that supplied list intentionally; separate copying is required for a return-new-list promise.

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

Reproduce cross-call state with a clean function

Call the original add helper twice without supplying items, beginning with a fresh definition in a clean process. The second result includes the earlier value, reproducing state retention without any external storage. Save an expectation that the two omitted-default calls return independent one-item collections. Then pass an explicit new list and compare behavior. This separates default ownership from other possible owners such as a global registry, closure, or caller-managed collection.

Inspect whether the function appends to the object it receives or merely rebinds a local name. Mutation changes the referenced list, whereas rebinding changes which object a local name refers to. A default list can therefore survive many calls through the function object even though each invocation has a fresh local namespace. A restart removes that particular process's function state, but restarting is not a repair for a helper that violates isolation during ordinary use.

Explain definition-time evaluation and the API decision

A default expression is evaluated when its function definition executes, not whenever an argument is omitted. The resulting list remains available as a default value, and each omitted call receives that same object. This is not a general rule that Python functions remember all local variables. It is an ownership relationship from the function's defaults to a mutable object, combined with append changing that object's contents.

Decide separately what an explicitly supplied list means. The reference keeps caller-supplied mutation: if a caller provides a list, add appends to that list and returns it. If the intended API promises a new result without changing caller data, make a copy under that different contract. A shallow list copy still shares nested items, so a non-mutating outer operation does not guarantee independent mutable descendants in the returned structure.

Repair omitted state without discarding explicit values

Using None as the default moves fresh list creation into the invocation when items is None. The example's first and second calls therefore print separate one-item lists. Test the condition by identity with None, not by truthiness. An explicit empty list is false in a Boolean context, but it is still an intentional caller-owned container; replacing it would silently change the reference contract for the caller.

If None is a meaningful explicit value distinct from omission, use a unique sentinel object and document both paths. A dataclass with per-instance mutable state uses a factory for the same underlying reason: creation must happen for each owner rather than once for the definition. Neither sentinel defaults nor factories automatically make shared caller inputs thread-safe. Concurrency policy and intentional shared state require separate coordination rather than another spelling of the default.

Verify isolation, explicit mutation and resource limits

Keep the first returned list, make a second omitted-default call, and assert that the first has not grown. For an explicit empty list, assert identity of the returned object and the caller's list if mutation is promised. Include explicit nonempty input and repeated calls with the same explicit list to show deliberate accumulation still works. Test unsupported input types through the declared validation policy instead of relying on an incidental missing-append exception.

The repaired omitted path allocates a fresh empty list per call and append has amortized constant-time growth for a list. A copy-on-call alternative costs O(n) for n existing elements and retains additional references. An intentionally accumulating cache needs a size or lifetime policy rather than an accidental default list. When reviewing the fix, distinguish accidental state removal from changing a useful API behavior, and avoid broad rewrites that obscure that choice.

Transfer question: The function must distinguish omitted items, explicit None, and an explicit empty list. How should the contract and tests change?

Introduce a private unique sentinel as the default. Omission creates fresh list state; explicit None follows a separately documented path, such as rejecting unavailable storage; and an explicit list retains the chosen mutation contract even when empty. Test all three paths plus repeated omitted calls and an explicitly reused list. Compare the argument with the sentinel by identity so an unusual caller object's equality implementation cannot impersonate omission. This solves argument interpretation, not arbitrary nested copying or concurrency, so those responsibilities should remain explicit rather than implied by the sentinel.

RECALL BEFORE YOU SCROLL

Can you explain it?

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

What should you do before adopting this repair?
TRANSFER THE IDEA

Recreate the repair independently

Test both omitted defaults and an explicitly supplied empty list. Start from the symptoms and write your own regression assertion before opening the reference.

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

Guided: fresh omission, deliberate supplied mutation

Fix default sharing without changing the explicit in-place append contract.

The contract

  • event is a string; events is omitted/None or a supplied list of strings.
  • Omission creates a new list; an explicit list is appended to in place and returned with the same identity.
  • Repeated omitted calls must not share state. An explicit empty list is still supplied input.
Guided: fresh omission, deliberate supplied mutationPYTHON 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. omitted
    assert append_event("a") == ["a"], "Create a list for omission"
  2. repeated omitted
    first = append_event("a")
    second = append_event("b")
    assert first == ["a"] and second == ["b"] and first is not second, "Omitted calls must be independent"
  3. explicit nonempty
    events = ["a"]
    result = append_event("b", events)
    assert result == ["a", "b"] and events == ["a", "b"] and result is events, "Append to the supplied list"
  4. explicit empty
    events = []
    result = append_event("a", events)
    assert result == ["a"] and events == ["a"] and result is events, "Empty input is not omission"
  5. explicit None
    assert append_event("a", None) == ["a"], "None selects fresh omitted state"
  6. repetitions
    events = ["a"]
    result = append_event("a", events)
    assert result == ["a", "a"] and result is events, "Keep repeated events"
    Why is copying the supplied list wrong in this first exercise?

    This contract deliberately promises in-place mutation for explicit input. The fix is about omission, not removing that capability. An append is amortized O(1), with occasional resize costs and no full source copy.

    GUIDED PRACTICE

    Guided: return a private event list

    Now implement the different contract that protects supplied input.

    The contract

    • event is a string; events is omitted/None or a list of strings.
    • Return a new list containing the supplied occurrences followed by event.
    • Never change or alias a supplied list; omitted calls and empty explicit inputs have independent results.
    Guided: return a private event listPYTHON 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. omitted
      assert private_event("a") == ["a"], "Create an omitted-call result"
    2. nonempty preserved
      events = ["a"]
      result = private_event("b", events)
      assert result == ["a", "b"] and events == ["a"] and result is not events, "Protect supplied contents"
    3. explicit empty
      events = []
      result = private_event("a", events)
      assert result == ["a"] and events == [] and result is not events, "Empty input must stay unchanged"
    4. repeated omission
      first = private_event("a")
      second = private_event("b")
      assert first == ["a"] and second == ["b"] and first is not second, "Do not share omitted state"
    5. duplicates
      assert private_event("a", ["a"]) == ["a", "a"], "Keep repeated occurrences"
    6. later result edit
      events = ["a"]
      result = private_event("b", events)
      assert result == ["a", "b"], "Start with the correct result"
      result.append("c")
      assert events == ["a"], "Later result edits must not affect input"
      Which new cost comes from the changed ownership promise?

      Copying n supplied entries adds O(n) time and storage. The final append is small on average, but the whole function is not O(1) for a supplied list.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: add to private grouped state

      The state now contains lists inside a dictionary. Separate both mutable levels before adding an event.

      The contract

      • name and event are strings; groups is omitted/None or a dict of string keys to string lists.
      • Return a new dict with event appended under name, creating that group when absent.
      • Preserve the supplied dict and all lists; every returned group list is independent, including repeated source aliases.
      Transfer: add to private grouped statePYTHON 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. omitted
        assert private_groups("api", "a") == {"api": ["a"]}, "Create fresh grouped state"
      2. existing group
        groups = {"api": ["a"]}
        result = private_groups("api", "b", groups)
        assert result == {"api": ["a", "b"]} and groups == {"api": ["a"]}, "Protect an existing group"
      3. new group
        groups = {"api": ["a"]}
        result = private_groups("worker", "b", groups)
        assert result == {"api": ["a"], "worker": ["b"]} and groups == {"api": ["a"]}, "Add the new key only to the result"
      4. empty supplied
        groups = {}
        result = private_groups("api", "a", groups)
        assert result == {"api": ["a"]} and groups == {} and result is not groups, "Keep explicit empty input private"
      5. all lists copied
        groups = {"api": ["a"], "worker": ["b"]}
        result = private_groups("api", "c", groups)
        assert result == {"api": ["a", "c"], "worker": ["b"]} and all(result[key] is not groups[key] for key in groups), "Copy unchanged groups too"
      6. source aliases separated
        shared = ["a"]
        groups = {"api": shared, "worker": shared}
        result = private_groups("api", "b", groups)
        assert result == {"api": ["a", "b"], "worker": ["a"]} and shared == ["a"] and result["api"] is not result["worker"], "Separate source aliases by group"
        What did the transfer requirement add beyond a None default?

        It added an ownership policy for an entire mapping of mutable lists. If n events are stored across u groups, copying every group uses O(n + u) time and result storage under ordinary dictionary assumptions.

        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

        The underlying mechanism

        Defaults are evaluated whenever the def statement executes, not necessarily once per process and not once per call. Rebinding a local name differs from mutating the retained default.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Functions created inside other functions or factories can have separate default lifetimes. Being precise avoids replacing one oversimplified explanation with another.

        Words you will see

        Function object
        The callable created by executing a definition.
        Rebinding
        Changing which object a local name refers to.
        Factory function
        A function that creates and returns another object, here another function.

        A new function can own a different default

        When make_adder executes an inner def, that new function receives its own newly evaluated list default. Calling make_adder twice therefore creates two function objects with two different default lists.

        Calls through one of those functions still share its default. This is not a recommendation to keep accidental state; it identifies the exact lifetime boundary. A deliberate stateful object or closure may express intended accumulation more clearly.

        An assignment can stop using a default without editing it

        items = items + [value] calculates a new list and then rebinds the local name. items.append(value) changes the existing object. The first does not grow the retained default, even though its parameter spelling still uses a mutable default.

        Avoid teaching rebinding as a broad cure: it can allocate a new list on every call and leave a misleading default in the signature. A clear sentinel and an explicit ownership policy are easier to maintain than relying on a subtle distinction hidden in the body.

        The original example, step by step

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

        1. first = make_adder()

          Execute one inner definition and create its default list.

        2. second = make_adder()

          Execute another inner definition with a different default list.

        3. print(first('b'))

          Reuse only first's retained list.

        4. print(second('c'))

          Second's state begins separately.

        Default expressions are evaluated when the function definition executes. The resulting object remains referenced by the function, so mutation is visible to future calls. This is separate from local-name rebinding.

        Predict before you run

        Does second's result contain a or b?

        Two definitions, two retained defaultsPYTHON 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.

        Make the shared source explicit.

        Try: Create one list outside make_adder and use that list as the inner default.

        Now separate definitions can intentionally retain the same external list.

        Use the repaired pattern.

        Try: Change the inner default to None and construct a list inside each call.

        Even repeated calls through first no longer accumulate previous omitted-call values.

        Before you move on

        If a function factory executes def twice, must those created functions share the same default list?

        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

        Not when the default expression constructs a list during each definition. Each created function retains its own list, though calls through the same function still share that function's default.

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

        Alternatives and operational trade-offs

        Fixing default lifetime and protecting caller-owned data are separate requirements. State which one the function promises, then copy only the needed mutable levels.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A patch can stop omitted calls sharing state while still unexpectedly editing explicit input. Conversely, blindly copying can break an API whose purpose is in-place editing.

        Words you will see

        In-place contract
        The supplied mutable object is intentionally changed.
        Return-new contract
        The function returns a new result and leaves input unchanged.
        Shallow ownership boundary
        Separating an outer container while retaining its nested object references.

        Define the caller-visible difference

        A private append function creates a fresh list for omission and copies a supplied list before appending. The caller can keep its original contents, and the result is a different outer list. Since the sample contains strings, no inner mutable objects require editing or copying.

        This is intentionally different from the earlier add repair, which preserves supplied-list mutation. Both can be valid APIs; they are not interchangeable. Names, documentation and tests should make the ownership policy visible.

        Carry the policy into deeper data

        A mapping of lists introduces two mutable levels: the mapping and each inner group. Copying only the outer dict can still append into a caller-owned group. A transfer task below therefore requests both a new mapping and a separate list for every group position.

        Copying n existing list entries uses O(n) work and storage even when the append itself is amortized O(1). Include the copy in the whole function's cost rather than reporting only the small final operation.

        The original example, step by step

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

        1. result = [] if items is None else items.copy()

          Choose fresh omitted state or a copied supplied outer list.

        2. result.append(value)

          Edit only the result list.

        3. print(source)

          The caller keeps its original a.

        4. print(answer is source)

          The independent result is not the supplied object.

        Using None fixes accidental default sharing, but does not make an explicitly supplied list private. If the API promises not to mutate caller data, make the required copy and document whether nested values remain shared.

        Predict before you run

        Does private_add change source?

        A separate return-new-list promisePYTHON 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.

        Remove the copy.

        Try: Use result = [] if items is None else items.

        The result aliases and edits a supplied list; omitted calls are still independent.

        Try empty explicit input.

        Try: Set source = [] before calling private_add.

        The result still has separate identity and source stays empty.

        Before you move on

        Does using items=None alone protect an explicitly supplied list from mutation?

        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

        No. It fixes omitted-state lifetime. Protecting a supplied list needs the separate decision to copy before editing under a return-new contract.

        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.