Skip to lesson content

← Python learning path

Module learning path

Python · essentials

When do two names point to the same changing data?

Lesson 2 of 8 · Collections, order, indexing and mutation

Ordered features and keyed records solve different identification problems; names may share one object.

Loading local progress…

Need a quick refresher?

Prerequisite recall: P01. Algebra functions · Statistics. Direct entry is allowed.

The full story · about 13 minutes

Collections: order, indexing and the copy that is not a copy

1 · Observe

One flat is a row of numbers

Words used in this lesson
WordWhat it means
ListAn ordered collection you can change.
TupleAn ordered collection that cannot change.
DictionaryA collection that looks values up by key.
AliasA second name for the same object.
CopyA new, independent object (a shallow copy still shares inner lists).

A flat has bedrooms, area and distance to the metro. Python holds such groups in collections: lists for ordered items you can change, tuples for ordered items you cannot, and dictionaries for items you look up by name. Choosing the right one decides what bugs are possible.

2 · Express

Indexing, slicing and mutation

list[0] is the first item, list[-1] the last
list[a:b] stops before b
a = b makes a second name for the same list; list(b) makes a copy
Lists are mutable: they can be changed in place. Tuples are not.

3 · Visualize

What happens

A list of three features [3, 80, 2.0]
OperationResult
features[0], features[-1]3 and 2.0
features[0:2][3, 80]
alias = features; alias[1] = 90features is now [3, 90, 2.0]
safe = list(features); safe[1] = 100features stays [3, 90, 2.0]
point[1] = 90 on a tupleTypeError

Assignment gives the same list two names, so editing through the alias changes the original. A copy is independent, but a shallow copy of a list of lists still shares the inner lists: changing one inner value changed both.

An alias edits the original; a copy does not
0255075100bedroomssizekmPosition in the listValue
  • Original (after alias edit)
  • Copy (edited to 100)
See the numbers behind this picture
An alias edits the original; a copy does not
Position in the listOriginal (after alias edit)Copy (edited to 100)
bedrooms33
size90100
km22

4 · Discover

Dictionaries

A dictionary maps keys to values: house['price_lakh'] = 65.0. A missing key raises KeyError, while house.get('age_years') returns None, or a default you provide. Use get when absence is normal.

5 · Apply

Two worked examples

Example 1, a hidden edit. A function receives features, sorts them in place, and the caller's data is reordered. Pass a copy when the function mutates.

Example 2, a lookup. house.get('age_years', 'unknown') records absence instead of crashing.

Check yourself

a = [1, 2]; b = a; b.append(3). What is a?

6 · Where it goes wrong

Three ways it goes wrong

7 · In Python

Collections in code

Here is how to implement it, step by step. The code below does exactly these steps, and every line is editable.

  1. Build a list in a fixed order, such as features = [3, 80, 2.0].
  2. Index with [0] and slice with [0:2].
  3. Copy with list(features) when you need an independent list.
  4. Use a tuple for values that must not change.
  5. Use a dict when you look up by name: house['price_lakh'], and .get() when absence is normal.
Indexing, aliasing, tuples, dicts and a shallow copy
features = [3, 80, 2.0]                  # bedrooms, size in sq m, km to metro
print("first:", features[0], "| last:", features[-1], "| slice:", features[0:2], "| length:", len(features))

alias = features
alias[1] = 90                           # assignment does not copy a list
print("after editing alias: original is", features)
safe = list(features)
safe[1] = 100
print("after editing a copy: original", features, "| copy", safe)

point = (3, 80, 2.0)                    # a tuple cannot change
try:
    point[1] = 90
except TypeError as e:
    print("tuple edit ->", type(e).__name__)

house = {"city": "Pune", "bedrooms": 3, "price_lakh": 62.5}
house["price_lakh"] = 65.0
print(house, "| keys:", list(house))
print("missing key with get:", house.get("age_years"), "| with default:", house.get("age_years", "unknown"))

rows = [[3, 80], [2, 60]]
shallow = rows.copy()
shallow[0][1] = 999
print("a shallow copy shares the inner lists:", rows)
first: 3 | last: 2.0 | slice: [3, 80] | length: 3
after editing alias: original is [3, 90, 2.0]
after editing a copy: original [3, 90, 2.0] | copy [3, 100, 2.0]
tuple edit -> TypeError
{'city': 'Pune', 'bedrooms': 3, 'price_lakh': 65.0} | keys: ['city', 'bedrooms', 'price_lakh']
missing key with get: None | with default: unknown
a shallow copy shares the inner lists: [[3, 999], [2, 60]]
Edit and run this code in your browser

Live Python

Indexing, aliasing, tuples, dicts and a shallow copy

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

Explore one controlled change

Experiment: trace one meaningful change

Pick a version of the program, predict exactly what it prints, then reveal the real output and say why. Change the configuration at least once to complete the activity.

features = [3, 10]
alias = features
copy = features.copy()
alias[0] = 4
print(features)
print(alias)
print(copy)
What will this program print?

Activity not yet demonstrated.

Why this matters

Ordered features and keyed records solve different identification problems; names may share one object.

Mathematical intuition: Ordered feature vectors; row identity differs from numeric position.

Terminology: list, tuple, dict, set, index, slice, key, reference, mutation.

Worked starting point: features=[2,10]; alias=features; alias[0]=3 changes features to [3,10]. features[-1] is 10; features[:1] is [3].

Now change the conditions: Reorder a feature pair and contrast alias versus copy after one edit.

Common misconception: A slice excludes its stop; aliasing is not an independent copy; a set has no feature-column order.

Essentials teaching and guided practice

Select an appropriate collection for ordered features, fixed pairs, keyed records and unique labels.

Ordered editable features can use a list; fixed pairs can use a tuple. Named fields use a dict; unique membership uses a set, never an assumed feature-column order.

Worked example

features = [3, 10]
record = {'area': 3, 'age': 10}
labels = {'spam', 'ham'}
print(type(features).__name__)
print(type(record).__name__)
print(type(labels).__name__)
list
dict
set
Edit and run this code in your browser

Live Python

P02.O1 worked

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

Not this: set ⏎ list ⏎ dict is a tempting but wrong answer. Rebuild a record using named keys and an ordered vector.

Success means: Match four ML data requirements to collection types.

Select an appropriate collection for ordered features, fixed pairs, keyed records and unique labels.

Not passed yet. Version A · 0 of 2 correct answers in a row.

Match four ML data requirements to collection types. Predict the result or error of this supplied program; preserve types, order and row identity.

features = [1, 10]
record = {'area': 1, 'age': 10}
labels = {'spam', 'ham'}
print(type(features).__name__)
print(type(record).__name__)
print(type(labels).__name__)
Result / reasoning outcome

Preserve feature order and identify shared-reference mutation.

features and alias name one mutable list; copy owns a separate list. Preserve the order [area, age].

Worked example

features = [3, 10]
alias = features
copy = features.copy()
alias[0] = 4
print(features)
print(alias)
print(copy)
[4, 10]
[4, 10]
[3, 10]
Edit and run this code in your browser

Live Python

P02.O2 worked

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

Not this: [3, 10] ⏎ [4, 10] ⏎ [4, 10] is a tempting but wrong answer. Draw two names pointing to one list, then copy it.

Success means: Predict both aliases after an edit and explain an independent-copy repair.

Preserve feature order and identify shared-reference mutation. — a key decision: choose, then explain

Not passed yet. Version A · 0 of 2 correct answers in a row.

Predict both aliases after an edit and explain an independent-copy repair. Predict the result or error of this supplied program; preserve types, order and row identity.

features = [1, 10]
alias = features
copy = features.copy()
alias[0] = 2
print(features)
print(alias)
print(copy)
Result / repair outcome
Explain why that outcome is justified

Predict positive/negative indexing and half-open slices.

Negative one selects the last position; the slice stop is excluded, so [:2] retains positions zero and one.

Worked example

features = [3, 5, 7]
print(features[-1])
print(features[:2])
7
[3, 5]
Edit and run this code in your browser

Live Python

P02.O3 worked

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

Not this: 3 ⏎ [3, 5, 7] is a tempting but wrong answer. Mark start-inclusive/stop-exclusive positions.

Success means: Select the exact resulting values from a changed sequence.

Predict positive/negative indexing and half-open slices.

Not passed yet. Version A · 0 of 2 correct answers in a row.

Select the exact resulting values from a changed sequence. Predict the result or error of this supplied program; preserve types, order and row identity.

features = [1, 3, 5]
print(features[-1])
print(features[:2])
Result / reasoning outcome

Use dictionary keys and set membership without relying on set iteration order.

Dictionary keys retrieve named fields; membership asks a yes/no question without relying on set iteration order.

Worked example

record = {'area': 3, 'age': 10}
labels = {'spam', 'ham'}
print(record['area'])
print('spam' in labels)
3
True
Edit and run this code in your browser

Live Python

P02.O4 worked

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

Not this: 10 ⏎ False is a tempting but wrong answer. Contrast position, key and membership tables.

Success means: Repair a preset keyed lookup or membership check.

Use dictionary keys and set membership without relying on set iteration order.

Not passed yet. Version A · 0 of 2 correct answers in a row.

Repair a preset keyed lookup or membership check. Predict the result or error of this supplied program; preserve types, order and row identity.

record = {'area': 1, 'age': 10}
labels = {'spam', 'ham'}
print(record['area'])
print('spam' in labels)
Result / reasoning outcome

Scoped lesson reset

Independent assessment · Essentials notebook. Neither lesson completion nor notebook use awards mastery.

Make the idea yours

Why can editing a list through one name change what another name sees? Contrast assignment with copying.

Explain the mechanism and give a small example. A matching output alone does not establish why it happened.

Check your explanation against the key distinction

A slice excludes its stop; aliasing is not an independent copy; a set has no feature-column order.

Unscored reflection; it does not add to your assessment record.
Read a larger ML expression
Equation X-Ray · Read the structure, then explain it

Mathematics as a language

One rule, many possibilities

A trip has a 3-rupee booking fee and costs 2 rupees per kilometre. How can one statement describe any permitted distance?

y = 2x + 3

Read the relationship before trying to solve it. This is an illustrative example, separate from the live experiment.

Choose a building block to inspect its role.

Read the operations: Multiply distance by its rate, then add the fee. If a bill is known, solving asks which distance makes both sides equal.

Build the expression from smaller operations

Choose a valid construction in the stated order. This exercise organizes dependencies; it does not claim every implementation must evaluate independent branches in this order.

    What problem could this relationship represent?

    A booking fee plus a distance charge is one possible interpretation; a fixed production setup cost plus a per-item charge has the same structure.

    Context we still need: Symbols alone do not establish currency, physical meaning or whether negative distances are allowed.

    Connect the operations to code
    bill = 2 * distance_km + 3

    Read the code as a map of operations. It is not executed here; imports, shapes and numerical safeguards depend on the actual lesson.

    Explain a changed situation

    Review the five-level equation-reading journey →

    Your notes and reveals are temporary. This reading practice does not change lesson completion or saved assessment evidence.

    Carry the idea forward

    Before continuing, explain what changed, why the code produced that result, and which assumptions mattered.