Menu
CoddyTech

Value Copies and Aliases

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

Swift Array has value semantics, implemented efficiently with copy-on-write. Nested arrays of integers preserve independent values when one copy changes. Python list.copy is shallow, so nested lists remain shared. Assignment alone shares even the outer list. Swift arrays containing class references can share the referenced objects too, so always inspect element semantics. Python sets remove duplicates without promising an iteration order; sort before producing ordered output.

Swift example

let original = [[1]]
var copied = original
copied[0].append(2)
print(original)
print(copied)

Python

original = [[1]]
copy = original.copy()
copy[0].append(2)
print(original)
print(sorted({3, 1, 3}))

Porting trap

Use set() for an empty Python set; braces without entries create a dict. Use explicit nested copying when independent nested lists are required.

Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.

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 Swift Developers

Practice on your own: Online Python compiler