Menu
CoddyTech

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 icon

Challenge

Beginner

Read 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__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for PHP Developers

Practice on your own: Online Python compiler