Duplicate and Shallow Copy
Lesson 15 of 48 in Coddy's Python for GDScript Developers course.
Godot Arrays and Dictionaries are shared by assignment. Array.duplicate makes an outer copy unless deeper copying is requested. Python list.copy is also shallow: nested lists remain shared. Python sets provide uniqueness for hashable values and have no promised iteration order. Godot projects often use dictionary keys to model a set; Python has a dedicated set type.
GDScript
extends SceneTree
func _init():
var a = [[1]]
var b = a.duplicate()
b[0].append(2)
prints(a[0].size(), b[0].size())
quit()Python
a = [[1]]
b = a.copy()
b[0].append(2)
print(len(a[0]), len(b[0]))Porting trap
Use set() for an empty Python set because {} creates a dictionary. Sort comparable set values before deterministic output. A deep-copy operation must be chosen deliberately for nested mutable data.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.
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 GDScript Developers
1From GDScript to Python
Run Your First Python ProgramPrint Is Not printsVar, Const, and BindingsInteger Division DifferencesSimilar Indentation, New ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and RebindingItems and enumerateWhile and Early ExitArray Callbacks and KeysRecap: Build a Ranking2Values and Decisions
Null and NoneThe is Keyword Changes MeaningLogical Results and OperandsConditional ExpressionsRecap: Eligibility Rules3Collections and Shared State
Array and List APIsArrays, Vectors, and TuplesDictionary Lookup RulesDuplicate and Shallow CopyRecap: Clean an Inventory6Input, Errors, and Modules
Console Work Outside GodotValidation and ExceptionsScript Resources and ImportsTyped GDScript and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler