Menu
CoddyTech

Shared References and Copies

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

Keep aliasing separate from copying. In Java, copying an object reference does not clone the object; Python assignment has the same practical sharing effect. list.copy makes a new outer list, like new ArrayList<>(original), while nested lists remain shared. Adding an outer element to the copy does not extend the original; mutating a shared nested element affects both views. A Python set removes duplicates but does not define a display order. Sort comparable values before producing deterministic output.

Java excerpt: inside main

var original = new java.util.ArrayList<java.util.List<Integer>>();
original.add(new java.util.ArrayList<>(java.util.List.of(1)));
var copy = new java.util.ArrayList<>(original);
copy.get(0).add(2);
System.out.println(original);

Python

original = [[1]]
copy = original.copy()
copy[0].append(2)
print(original)
print(sorted({3, 1, 3}))

Watch the difference

Neither a shallow copy nor Java final makes nested state independent. Use set() for an empty set: {} creates an empty dictionary. Do not grade or rely on an arbitrary set print order.

Practice

Apply this comparison in the task below. 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.

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 Java ArrayList copy constructor, copying the outer container does not clone nested 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 Java Developers

Practice on your own: Online Python compiler