Destructuring and Tuples
Lesson 13 of 48 in Coddy's Python for PHP Developers course.
PHP array destructuring assigns several variables with a bracketed pattern. Python can unpack any suitable iterable using comma-separated names. A tuple groups positional values without making their slots assignable. The comma makes the tuple: (3,) is a one-item tuple, but (3) is an integer. Swapping with x, y = y, x evaluates the right side before assigning either name. PHP arrays remain mutable; a Python tuple cannot have an element replaced.
PHP 8.3
<?php
$point = [3, 8];
[$x, $y] = $point;
[$x, $y] = [$y, $x];
echo $x, ' ', $y, "\n";Python
point = (3, 8)
x, y = point
x, y = y, x
print(x, y)Porting trap
Tuple immutability applies to slots, not every reachable object. A list inside a tuple can still be changed. Unpacking two names requires exactly two values unless a starred target collects extras.
Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.
Challenge
BeginnerRead an integer horizontal coordinate and an integer vertical coordinate on two lines. The scaffold packs them into a tuple named point. Unpack the coordinates, swap their order, then print the original tuple followed by the swapped tuple on separate lines. Values are from -100 to 100; use Python tuple 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