dup, Copies, and Sets
Lesson 15 of 48 in Coddy's Python for Ruby Developers course.
Ruby dup and Python list copy make a new outer container with shared element objects. Assignment shares the outer object too. If you mutate a nested list through a shallow copy, the original sees the change. Replacing an outer slot is different because the outer containers are independent. Ruby requires the standard-library set implementation for Set; Python has a built-in set. Both remove duplicate elements, but do not use set iteration order as a portable output contract. Sort comparable elements before printing. Python {} is an empty dictionary, so construct an empty set with set().
Ruby
a = [[1]]
b = a.dup
b[0] << 2
p aPython
a = [[1]]
b = a.copy()
b[0].append(2)
print(a)
print(sorted({3, 1, 3}))Porting trap
A shallow copy is not a backup of nested mutable state. Copy each needed level or use copy.deepcopy when recursive independence is required.
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 Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler