Menu
CoddyTech

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

Practice on your own: Online Python compiler