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
BeginnerRead 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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Dart Developers
1From Dart to Python
Run Your First Python ProgramInterpolation and printvar, final, and Python NamesFloor Versus TruncationBraces and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for-in and rangeentries and enumerateLoop Updates and continuewhere, map, and List BuildingRecap: Build a Ranking2Values and Decisions
Null Safety and NoneList Equality ChangesConditions and Null DefaultsTernaries and elifRecap: Eligibility Rules3Collections and References
Lists and Negative IndexesRecords and Tuple UnpackingMap Lookups and KeyErrorSets and Shared ObjectsRecap: Clean an Inventory6Reliable Python Programs
stdin and Exact Formattingon, catch, finally, and withLibraries and Import ExecutionStatic Types Versus HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler