Menu
CoddyTech

Sets and Shared Objects

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

Dart and Python both provide sets for unique elements and mutable lists whose assignments share references. A copied outer list still shares nested mutable elements unless those are copied too. Dart List.from and a spread copy are shallow in this sense, as is Python list.copy. Python set iteration order is not a portable output contract; sort comparable values before printing. Python empty braces create a dict, while set() creates an empty set. Dart typed set literals can disambiguate an empty set from a map. In both languages, immutability of a variable binding is separate from the mutability of an object it references.

Dart

void main() {
  final a = [[1]];
  final b = List<List<int>>.from(a);
  b[0].add(2);
  print(a);
}

Python

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

Porting trap

A shallow copy protects the outer list structure only. Nested mutations can remain visible through the original.

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

Practice on your own: Online Python compiler