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
BeginnerRead 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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Swift Developers
1From Swift to Python
Run Your First Python ProgramPrinting and Stringslet, var, and RebindingInt Range and DivisionIndentation and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for and Half-Open Rangesenumerated to enumeratewhile and Loop Controlmap, filter, ComprehensionsRecap: Build a Ranking2Values and Decisions
Optionals and NoneEquatable and IdentityBool Conditions and FallbacksBranches and TernariesRecap: Eligibility Rules3Value Types to Shared Objects
Array to listTuples and UnpackingDictionary Lookup and OrderValue Copies and AliasesRecap: Clean an Inventory6Errors and Modules
Input and String Formattingthrows, defer, and withModules and Main GuardsHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler