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 09 / COLLECTIONS IN DEPTH

Tuples and useful unpacking

Represent fixed records and unpack meaningful pieces.

FoundationTutorial 9 min core+6 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: 9 minutes; optional deep dive: 6 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 and unpack tuples
  • Use starred unpacking
  • Understand shallow immutability
01

A fixed-shaped record

A tuple keeps several values in a fixed sequence. You can read its positions, but you cannot replace, add or delete its own entries after creation.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use a tuple when positions have a stable meaning, such as x and y in a coordinate or the two values returned from one calculation. A list is usually better for a collection you keep growing.

Words you will see

Sequence
Values with positions in a defined order.
Immutable
The tuple's own entries cannot be changed in place.
Unpacking
Assigning the entries of an iterable to several target names.

The comma matters more than the parentheses

(3, 7) makes a two-item tuple. (5,) makes a one-item tuple; its trailing comma matters. (5) is simply the integer 5 grouped in parentheses. () is the empty tuple. The spelling 3, 7 can also create a tuple, but parentheses often make the intended grouping clearer.

Read positions with point[0] and point[-1], count items with len(point), and read a slice with point[:1]. A single-item read needs an existing position. An out-of-range index raises IndexError; an empty selection can give an empty tuple.

Name the values instead of memorising offsets

x, y = point assigns the first value to x and the second to y. Ordinary unpacking requires exactly two values here. Too few or too many raises ValueError instead of silently dropping data. Unpacking is not unique to tuples; it also works with lists and other iterables.

first, *rest = [10, 20, 30] gives first the value 10 and gathers remaining values into a list [20, 30]. A starred target is a list even if the input was a tuple. Without a starred target, every supplied value must have a matching target.

Choose a record, not a vague pile of fields

A coordinate's two positions have clear meaning. A ten-field tuple accessed through unexplained numbers does not. Prefer named fields when positions become difficult to remember. Fixed outer shape does not promise that objects stored inside are also immutable; optional depth makes that distinction concrete.

The original example, step by step

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

  1. point = (3, 7)

    Create an ordered two-value coordinate.

  2. x, y = point

    Bind x to 3 and y to 7, without changing point.

  3. first, *rest = [10, 20, 30]

    Take the first value and gather the remaining values into a new list.

  4. print(first, rest)

    Display 10 [20, 30], not a tuple for rest.

A tuple is an immutable sequence, useful for coordinates or multiple function results. The comma creates a tuple: (5,) is a one-element tuple; (5) is just an integer in parentheses.

Which object is changing?

A conceptual ownership model, not a recording of your Python run. The tuple keeps a name and a reference to the skills object.

  1. index 0refers toAda
  2. index 1refers toinner list

["python"]

The outer pair keeps its two entries; the skills object is initially a list.

Predict before you run

What kind of value is rest?

Name a coordinatePYTHON 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 exact unpacking with the wrong shape.

Try: Replace x, y = point with x, y, z = point.

The actual run reports ValueError because there are only two values.

Make a one-item tuple.

Try: Compare print(type((5))) with print(type((5,))).

The first is int; the second is tuple.

Before you move on

What are the types of (9), (9,), and rest after head, *rest = (1, 2, 3)?

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

(9) is an integer; (9,) is a tuple. head becomes 1 and rest is the list [2, 3]. The comma creates the one-item tuple and the star collects remaining items into a list.

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

Make shape visible

Unpacking makes a record's shape visible at the place it is used. Use meaningful names and check the number of fields you expect.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A caller can understand name, count, region immediately. Repeated record[0], record[1] and record[2] force the reader to remember a hidden agreement.

Words you will see

Shape
The expected number and meaning of fields.
Starred target
The one target at this unpacking level that collects leftover values.
Named record
A structure with field names, such as a named tuple or dataclass.

Unpacking expresses an agreement

name, count, region = record requires exactly three values in that order. The target names do not inspect or validate types automatically. If the third value is an integer instead of a region string, unpacking still succeeds; type or business validation is a separate decision.

Use at most one starred target at each unpacking level. first, *middle, last requires at least two values and lets the middle be empty. Nested targets can unpack nested shapes, but each level must fit the supplied data. Using _ merely chooses a variable name by convention; it is not special discard syntax.

Keep the meaning visible as records grow

Return a small tuple when the relationship is clear and stable. A namedtuple can preserve fixed sequence behavior while offering attributes. A dataclass can make field definitions, defaults and methods clearer for a larger record; it is not automatically immutable.

Do not silently change a published pair into a triple: existing callers using two targets will fail. Shape is part of an interface. Converting any iterable with tuple(...) also consumes it; for an iterator this can exhaust values rather than creating a harmless view.

The original example, step by step

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

  1. name, count, region = record

    Give a meaningful local name to each of the three positions.

  2. first, *middle, last = record

    Keep Ada and EU as endpoints; gather [7] as a list in the middle.

  3. short = ("Ada", "EU")

    Create only the two required endpoint values.

  4. print(middle)

    The final starred middle is [], not an unpacking error.

Unpack returned pairs instead of repeatedly using [0] and [1]. A tuple is best when position has a clear meaning; a dataclass or named record can be clearer when the number of fields grows.

Predict before you run

What does the last print show?

Unpack a record and its middlePYTHON 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 middle longer.

Try: Use record = ("Ada", 7, 8, "EU") and change the first exact unpacking to name, *counts, region = record.

The star accommodates the extra middle value; the original exact three-target unpacking would fail.

Expose a missing endpoint.

Try: Change short to ("Ada",).

One value cannot fill both first and last, so the run reports ValueError.

Before you move on

Can first, *middle, last unpack a one-item tuple? Does middle become a tuple when it succeeds?

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

A one-item input has too few values for the two endpoints, so it raises ValueError. When it succeeds, middle is a list, possibly empty.

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

Swapping evaluates before binding

In a multiple assignment, Python evaluates the right-hand values before assigning the left-hand names. That makes a swap different from two sequential assignments.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Swapping names is common in algorithms, but it is also a useful way to understand evaluation order and the difference between names and stored objects.

Words you will see

Evaluate
Compute or retrieve a value on the right-hand side.
Bind / rebind
Make a name refer to a value, or change which value it refers to.
Sequential assignment
A later statement reads the state left by earlier statements.

Trace the old values before writing names

For left, right = right, left, first read the old right, blue, and the old left, red. Then assign those two values to left and right in that order. Neither read sees a half-finished swap.

With left = right followed by right = left, the first statement makes left refer to blue. The second then reads that new left and also gives right blue. The original red is no longer available through either name.

A swap changes bindings, not the objects themselves

Swapping two variables that name lists does not copy or edit either list. It exchanges which list each name refers to. Other names for those lists still refer to the same objects as before.

The same principle supports a, b = b, a + b, because the calculation uses old a and b. Prefer explicit small assignments when a larger expression hides important side effects. The goal is readable evaluation order, not a clever one-line trick.

The original example, step by step

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

  1. left, right = "red", "blue"

    Start with two different string values.

  2. left, right = right, left

    Read both old bindings, then bind left to blue and right to red.

  3. left = right

    In the second demonstration, overwrite left before the next statement reads it.

  4. right = left

    Read the already changed left, producing blue blue.

a, b = b, a evaluates the right-hand values before rebinding either name. No explicit temporary name is required.

Predict before you run

Why does the second demonstration print blue blue?

A swap versus overwritten informationPYTHON 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.

Swap numeric values.

Try: Replace the colour strings with 2 and 3.

The binding rule stays the same; it is not specific to strings.

Use old values in a calculation.

Try: Try a, b = 2, 3 followed by a, b = b, a + b and print(a, b).

The result is 3 5 because both calculations use the old bindings.

Before you move on

Starting with a = 2 and b = 3, what does a, b = b, a + b 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

The old right-hand values are 3 and 5, so a becomes 3 and b becomes 5. The addition uses old a = 2, not the newly assigned a = 3.

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

Where this idea earns its place

A tuple fits a fixed-shape positional record such as coordinates or a pair returned by a function. Its value is not merely being a list with different punctuation: preventing slot replacement communicates a structural promise. When field meanings are hard to remember, a named record or dataclass can be clearer than a long tuple.

Follow the mechanism step by step

The comma creates the tuple; parentheses often only group an expression. In x, y = point, Python first obtains values and then binds the targets. Exact unpacking requires the expected arity, while a starred target collects remaining values into a list. A tuple can still contain references to mutable objects, whose contents remain changeable.

Work through a concrete application

Trace swapping with left, right = right, left: both right-side references are obtained before either target changes. Next return a result and an error count as a pair, and unpack them into meaningful names at the call site. If optional extra fields appear later, reconsider a rigid positional contract instead of scattering numeric indexes throughout callers.

Failure cases and misleading shortcuts

A tuple containing a list is not deeply immutable and cannot be hashed as a dict key. Calling tuple(existing_iterable) consumes it; converting an exhausted iterator yields an empty tuple. An accidental missing comma changes a one-item tuple into the enclosed value, which can alter iteration or function argument behaviour in subtle ways.

Cost, ownership and alternatives

Indexing is O(1), membership can scan O(n), and constructing a new tuple generally stores references to all elements. Converting a list to a tuple is not a free deep freeze or a way to eliminate large referenced objects. Choose semantics first, then measure representation costs only where the workload justifies it.

Verify the contract

Test arity mismatches and the single-item case. If the tuple serves as a key, verify that every nested component is hashable and semantically stable. For a public return type, add a caller-level test that names the expected fields so a future reordering does not silently swap meanings.

Transfer question: Can a tuple of coordinates safely serve as a dictionary key?

Yes when its components are hashable values with stable equality semantics, such as two integers. A tuple containing mutable lists does not become hashable merely because the outer container is a tuple. Consider a named immutable model if the key gains additional fields.

RECALL BEFORE YOU SCROLL

Can you explain it?

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

Which is a one-element tuple?
TRANSFER THE IDEA

Swap two names

Swap left and right with unpacking.

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: return a reversed pair

Return the two supplied values in opposite order without editing the input.

The contract

  • Input is a tuple containing exactly two values.
  • Return a tuple of those same values in reverse order.
  • Do not modify nested values or convert the result into a list; equal values are valid.
Guided: return a reversed pairPYTHON 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. two integers
    assert swap_pair((2, 3)) == (3, 2), "Reverse the pair"
  2. strings
    assert swap_pair(("red", "blue")) == ("blue", "red"), "Do not hard-code numbers"
  3. equal values
    assert swap_pair((4, 4)) == (4, 4), "Equal entries are valid"
  4. tuple result
    assert isinstance(swap_pair((1, 2)), tuple), "Return a tuple"
  5. mixed values
    assert swap_pair(("Ada", 7)) == (7, "Ada"), "Keep the values intact"
  6. nested ownership
    inner = ["x"]
    result = swap_pair(("Ada", inner))
    assert result[0] is inner and inner == ["x"], "Swap references without editing the inner object"
    Does this need a deep copy?

    No. The contract reorders two references without editing the referenced objects. For a fixed two-item pair, work and outer result space are O(1).

    GUIDED PRACTICE

    Guided: separate endpoints and middle

    Use starred unpacking without assuming the middle contains an item.

    The contract

    • Input is a tuple containing at least two values.
    • Return a three-item tuple: the first value, a list of all middle values, and the last value.
    • Preserve input order and repeated values; the middle list is independently created for each call.
    Guided: separate endpoints and middlePYTHON 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. three values
      assert split_record(("Ada", 7, "EU")) == ("Ada", [7], "EU"), "Collect the middle"
    2. empty middle
      assert split_record(("Ada", "EU")) == ("Ada", [], "EU"), "An empty middle is valid"
    3. long middle
      assert split_record((1, 2, 3, 4, 5)) == (1, [2, 3, 4], 5), "Collect every middle value"
    4. duplicates
      assert split_record((1, 1, 1, 1)) == (1, [1, 1], 1), "Keep repetitions"
    5. types
      result = split_record((1, 2))
      assert isinstance(result, tuple) and isinstance(result[1], list), "Use the promised outer and middle types"
    6. independent result
      record = (1, 2, 3)
      a = split_record(record)
      b = split_record(record)
      a[1].append(9)
      assert record == (1, 2, 3) and b[1] == [2], "Do not share result middle lists"
      Why is the middle not immutable just because the input was a tuple?

      Starred unpacking creates a list by language rule. For n input values, gathering the middle uses O(n) time and O(n) additional storage; it does not deeply copy the selected objects.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: represent an edited tuple

      Tuples cannot be edited in place. Return the value that an index replacement would represent.

      The contract

      • Input is a tuple, an integer index and a replacement value.
      • Return a tuple with only that position replaced; support valid positive and negative indexes.
      • Preserve the input. Raise IndexError for any index outside the tuple, including every index on an empty tuple. Object identity of an unchanged immutable result is not prescribed.
      Transfer: represent an edited tuplePYTHON 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. middle
        assert replace_tuple_item((1, 2, 3), 1, 9) == (1, 9, 3), "Replace only the selected entry"
      2. negative
        assert replace_tuple_item((1, 2, 3), -1, 9) == (1, 2, 9), "Support negative indexing"
      3. first negative boundary
        assert replace_tuple_item((1, 2), -2, 8) == (8, 2), "Allow the first negative boundary"
      4. immutable source
        record = ("a", "b")
        assert replace_tuple_item(record, 0, "c") == ("c", "b") and record == ("a", "b"), "Preserve the source"
      5. invalid boundaries
        for index in (2, -3):
            try:
                replace_tuple_item((1, 2), index, 9)
            except IndexError:
                continue
            raise AssertionError("Invalid indexes must raise IndexError")
      6. empty tuple
        try:
            replace_tuple_item((), 0, 9)
        except IndexError:
            pass
        else:
            raise AssertionError("An empty tuple has no position zero")
        Why is a slice-only solution not enough?

        Slice boundaries clip instead of raising for invalid positions, so validate the index first. Rebuilding an n-item outer tuple takes O(n) time and O(n) result storage; nested values remain shared unless separately copied.

        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

        Immutable container, possibly mutable contents

        A tuple cannot change its own entries, but an entry can refer to a list that changes. Hashability and deep immutability are separate questions.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        An immutable wrapper does not automatically make a record safe to share without an ownership policy. This matters for function returns, dictionary keys and cached values.

        Words you will see

        Outer entry
        One of the references stored directly in the tuple.
        Nested mutation
        Changing a mutable object reached through an entry.
        Hashable tuple
        A tuple whose elements are all hashable, allowing its hash to be calculated.

        Locate the actual write

        record[1].append("sql") first reads the list in the second tuple position, then edits that list. The tuple still refers to the same list. record[0] = "Lin" instead attempts to replace an outer entry and raises TypeError.

        A tuple containing a list cannot be hashed. A tuple of strings and integers usually can. An immutable outer container is therefore not enough for a dictionary key: every item must meet the hashing contract.

        Decide which level may be shared

        If another caller may append to the skills list, returning the same list inside a tuple shares that capability. Copy the list when independent editing is required, or deliberately use a tuple of skill strings if changes should require building a new value.

        Be particularly careful with record[1] += [...]: list addition-in-place can change the inner list before the later attempt to assign that list back into a tuple position fails. A raised exception does not always mean no change occurred. Prefer an explicit operation with a clear ownership 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. record = ("Ada", ["python"])

          Create a fixed outer pair containing a mutable inner list.

        2. record[1].append("sql")

          Change the inner list without replacing a tuple entry.

        3. record[0] = "Lin"

          This outer replacement is rejected and caught.

        4. hash(record)

          Hashing fails because one element is an unhashable list.

        A tuple cannot replace its own element references, but a list inside a tuple can still mutate. Hashability depends on its elements: a tuple containing a list cannot serve as a dict key.

        Predict before you run

        Does appending sql succeed?

        A fixed tuple with a changing 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.

        Change one thing; explain the difference.

        Use an immutable skills sequence.

        Try: Replace ["python"] with ("python",).

        The append call now fails because tuples have no append method; immutability changed at the inner level.

        Observe the augmented-assignment trap.

        Try: Replace the append statement with a caught record[1] += ["sql"], then print(record).

        The inner list can change before tuple reassignment raises TypeError. Catching an error is not proof of rollback.

        Before you move on

        Which can be a key: ("EU", 7) or ("EU", [7])? Can the inner list of the second tuple still be edited?

        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 tuple is hashable. The second is not, because its list is unhashable. That inner list can be edited even though the outer tuple's entries cannot be replaced.

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

        Costs and design

        Choose tuples for stable sequence meaning, not as a universal speed trick. Reading, searching and rebuilding have different costs.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A record type should express your API's promises. A fixed sequence is helpful when stable shape matters; large repeated rebuilds may suggest another design.

        Words you will see

        Concatenation
        Joining sequences into a result with +.
        O(1)
        Work that does not grow with the number of tuple entries, under the stated assumptions.
        O(n)
        Work that can grow in proportion to n entries.

        Separate direct access from a search or rebuild

        Reading an existing tuple position is O(1). Membership, index and count may inspect n entries, making them O(n) with bounded comparison cost. index raises ValueError when no match exists; count gives zero. Slicing k selected entries typically needs O(k) work and storage.

        Building a changed n-entry tuple generally needs O(n) work and result storage. Some implementations can reuse an existing immutable tuple for particular operations, so do not use object identity as a general test that a logically unchanged value was copied.

        A fixed record is an interface decision

        A coordinate that should remain a two-part value is a good tuple candidate. A growing task queue usually wants a different collection. Named tuples and frozen dataclasses can express field meaning, but neither label promises recursive immutability for nested values.

        When reporting space, distinguish a new outer sequence of references from new copies of all objects. The example's concatenation rebuilds outer references; it does not deeply copy arbitrary nested objects. Choose semantics first, then measure performance if a real workload makes it important.

        The original example, step by step

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

        1. point = (3, 7)

          Keep the original fixed coordinate.

        2. changed = (9,) + point[1:]

          Join a one-item tuple with the remaining slice to form (9, 7).

        3. print(7 in point)

          Search for a matching value; display True.

        4. print(point.index(7))

          Display the first matching zero-based position, 1.

        Tuple indexing is O(1); membership is O(n); a new tuple generally allocates references for its elements. Choose tuples for a stable shape, not an assumption that all nested data is frozen.

        Predict before you run

        What is point after changed is created?

        Build a changed coordinatePYTHON 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.

        Replace the second coordinate instead.

        Try: Use changed = point[:1] + (9,).

        The result is (3, 9); the original stays (3, 7).

        Ask for an absent value.

        Try: Compare point.count(99) with a caught point.index(99).

        count gives zero, while index raises ValueError.

        Before you move on

        Does changing one represented value in a tuple mean the original tuple was edited? Is membership direct indexing?

        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: a changed result can be built while the original stays intact. Membership searches values and can examine many entries; reading a known valid index directly selects one position.

        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.