Menu
CoddyTech

Sets and Shallow Copies

Lesson 15 of 48 in Coddy's Python for Go Developers course.

Copying a Go slice of slices into fresh outer storage copies inner slice headers, not the inner backing arrays. Python list.copy likewise makes a shallow outer copy. In both examples inner mutation is visible through a, while extending b leaves the outer length of a unchanged. Go commonly models a set with map[T]struct{}; Python has a built-in set with membership, add, and duplicate removal.

Go

Go excerpt inside main; imports: fmt. The verification bundle contains the complete program.

// Inside main:
a := [][]int{{1}}
b := append([][]int(nil), a...)
b[0][0] = 7
b = append(b, []int{9})
seen := map[int]struct{}{1: {}, 7: {}}
seen[1] = struct{}{}
fmt.Println(a, b, len(seen))

Python

a = [[1]]
b = a.copy()
b[0][0] = 7
b.append([9])
print(a, b, len({1, 7, 1}))

Porting trap

Python set iteration is not a sorted-output contract. Sort before displaying a set deterministically. Also {} means an empty dict; use set() for an empty set.

challenge icon

Challenge

Beginner

Read initial, replacement, and extra integers in [-20,20]. The scaffold makes a nested list, an alias, and a shallow copy. Through the alias replace the inner integer. Append [extra] only to the outer copy. Output the original nested list, the copy, and a sorted list of the three distinct input values, each on its own line. As with a copied Go slice of slices, the outer copy still shares nested mutable objects.

Editable files: main.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

Keep the supplied input scaffold. Output only the requested results, with a newline after each line and no prompts.

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

Practice on your own: Online Python compiler