Menu
CoddyTech

Sets, Aliasing, and Copies

Lesson 15 of 48 in Coddy's Python for JavaScript Developers course.

Remove duplicates and predict which changes are shared after an assignment or shallow copy.

JavaScript

const original = [[4]];
const alias = original;
const shallow = original.slice();
alias[0][0] = 9;
console.log(shallow[0][0]);
console.log(new Set([4, 4, 9]).size);

Python

original = [[4]]
alias = original
shallow = original.copy()
alias[0][0] = 9
print(shallow[0][0])
print(len({4, 4, 9}))

What changes

Both programs print 9 and 2. Assignment adds a name for the existing list; it does not copy that list. copy() or a full slice creates a new outer list but retains references to the same items. When an item is another list, a nested change remains visible through both outer lists. Appending to just one outer list does not append to the other. For a known two-level shape, explicitly copying each inner list can isolate those inner mutations. A set keeps unique hashable values. Construct one with {1, 2} or set(existing_list); the empty set is set(), because {} creates a dictionary.

Common mistake

A shallow copy is not a recursive snapshot. Also, sets are not indexable sequences and have no guaranteed display order. For deterministic numeric output, sorted(values) returns a new ascending list; use it before printing a set. Lists cannot be set members because they are unhashable.

Your task

Modify shared nested state, add an outer item only to the copy, and print sorted unique input values. Each output exposes a different reference or uniqueness rule.

challenge icon

Challenge

Beginner

Read three integers on separate lines: an initial value, a replacement, and an extra value, each from -20 to 20. The scaffold creates a nested list, an alias of it, and a shallow copy. Through the alias, replace the nested integer with the replacement. Append [extra] to the shallow copy only. Print the original nested list, the shallow copy, and a sorted list of the distinct three input integers, each on its own line. Use Python list format.

Print only the requested output, with a newline after each line. Keep the supplied input scaffold. No loops or functions are needed.

Your code goes in main.py. The locked driver.py starts your program and cannot be edited.

Try it yourself

# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module

run_module("main", run_name="__main__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for JavaScript Developers

Practice on your own: Online Python compiler