Array Copies and List Aliases
Lesson 15 of 48 in Coddy's Python for PHP Developers course.
Ordinary PHP array assignment behaves as a value copy; copy-on-write is an implementation optimization. Python b = a shares one list. Python a.copy() copies only the outer list, leaving nested lists shared. PHP arrays can also contain explicit references or objects, so do not assume all reachable PHP state is deeply independent. Python sets retain unique hashable values without a promised iteration order. Use set() for an empty set, since {} is an empty dictionary.
PHP 8.3
<?php
$a = [[1]];
$b = $a;
$b[0][] = 2;
echo count($a[0]), ' ', count($b[0]), "\n";Python
a = [[1]]
b = a.copy()
b[0].append(2)
print(len(a[0]), len(b[0]))Porting trap
When deterministic output is required, sort a set's comparable items. For independent nested Python lists, copy the nested lists too or use copy.deepcopy where appropriate.
Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.
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 PHP Developers
1From PHP to Python
Run Your First Python ProgramEcho, Strings, and printVariables Without Dollar SignsDivision and Numeric TextIndentation and SuitesRecap: Rewrite a Receipt4Iteration and Transformations
Foreach and rangeKeys, Items, and enumerateWhile Without IncrementFilters and Sort KeysRecap: Build a Ranking2Values and Decisions
Null, None, and Missing KeysStrict Equality Is Not isThe Zero String TrapElif and Value SelectionRecap: Eligibility Rules3Arrays and Python Collections
PHP Arrays and Python ListsDestructuring and TuplesKeys, Null, and getArray Copies and List AliasesRecap: Clean an Inventory6Input, Errors, and Modules
CLI Input and Exact OutputConversion Errors and CleanupImports Instead of requireType Hints Are Not PHP TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler