Shallow Copies and Sets
Lesson 15 of 48 in Coddy's Python for Kotlin Developers course.
Kotlin toMutableList and Python list.copy create new outer containers while sharing referenced elements. Assignment alone shares a mutable list in both languages. Nested lists therefore remain connected after a shallow copy. Kotlin read-only collection interfaces do not recursively freeze those elements. Python sets collect unique hashable values and do not promise iteration order; sort comparable elements for stable output.
Kotlin
fun main() {
val a = mutableListOf(mutableListOf(1))
val b = a.toMutableList()
b[0].add(2)
println("${a[0].size} ${b[0].size}")
}Python
a = [[1]]
b = a.copy()
b[0].append(2)
print(len(a[0]), len(b[0]))Porting trap
Python {} constructs a dictionary, not a set. Use set() for an empty set and an explicit nested copy or deepcopy when nested state must be independent.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.
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 Kotlin Developers
1From Kotlin to Python
Run Your First Python ProgramPrint and String TemplatesVal, Var, and Python NamesDivision and Integer WidthSuites and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and Loop BindingsEntries and withIndexUpdates and Loop ControlCollection PipelinesRecap: Build a Ranking2Values and Decisions
Nullable Types and NoneEquality and IdentityBoolean Conditions and orIf Expressions and ElifRecap: Eligibility Rules3Collections and Shared State
Read-only Lists and MutationPair and Tuple UnpackingMap Lookup and Missing KeysShallow Copies and SetsRecap: Clean an Inventory6Input, Errors, and Modules
Console Input and FormattingExceptions and Resource ScopeImports and Entry PointsStatic Types and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler