Menu
CoddyTech

Sets, Aliases, and Copies

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

Predict which changes are shared through aliases and shallow copies.

C# reference excerpt

Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.

var a = new System.Collections.Generic.List<System.Collections.Generic.List<int>> { new System.Collections.Generic.List<int> { 1 } };
var b = new System.Collections.Generic.List<System.Collections.Generic.List<int>>(a);
b[0][0] = 9;
Console.WriteLine(a[0][0]);

Python

a = [[1]]
b = a.copy()
b[0][0] = 9
print(a[0][0])

What changes

Assigning a Python name shares an object, like assigning a C# class reference. list.copy creates a new outer list, like a List<T> copy constructor, while retaining references to nested lists. Python set is a uniqueness collection analogous to HashSet<T>. Use set() for an empty set; {} makes a dictionary. Sort set elements when output order matters.

Transfer mistake

Do not carry the C# struct-copy mental model into arbitrary Python assignment. A shallow copy is not an independent nested object graph.

Your task

Read initial, replacement, and extra integers in [-20, 20]. The scaffold supplies a nested list, an alias, and a shallow copy. Use the alias to replace the nested integer. Append [extra] only to the shallow outer copy. Output the original nested list, the shallow copy, and a sorted list of distinct input integers on three lines. Use Python list formatting.

challenge icon

Challenge

Beginner

Read initial, replacement, and extra integers in [-20, 20]. The scaffold supplies a nested list, an alias, and a shallow copy. Use the alias to replace the nested integer. Append [extra] only to the shallow outer copy. Output the original nested list, the shallow copy, and a sorted list of distinct input integers on three lines. Use Python list formatting.

Editable implementation files: main.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Use the supplied input contract without prompts. Print only the required lines, each ending in a newline.

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 C# Developers

Practice on your own: Online Python compiler