Clone and Shallow Copies
Lesson 15 of 48 in Coddy's Python for Rust Developers course.
Rust cloning Vec<Vec<i32>> clones the inner vectors too. Python list.copy only makes a new outer list and leaves inner objects shared. Plain Python assignment shares even the outer list. Rust shared ownership types such as Rc can also share underlying state, so inspect the actual element type before equating Clone with deep copying. Python sets remove duplicates and have no promised iteration order. Use sorted when comparable set elements must be printed deterministically.
Rust excerpt inside main
let original = vec![vec![1]];
let mut copied = original.clone();
copied[0].push(2);
println!("{:?}", original);
println!("{:?}", copied);Python
original = [[1]]
copy = original.copy()
copy[0].append(2)
print(original)
print(sorted({3, 1, 3}))Porting trap
Python {} is an empty dictionary, not a set. Use set() for an empty set and explicit nested copies or copy.deepcopy for independent nested mutable objects.
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 Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler