Menu
CoddyTech

Tuples and Unpacking

Lesson 13 of 48 in Coddy's Python for JavaScript Developers course.

Keep a fixed sequence in a tuple and unpack its values into names.

JavaScript

let [left, right] = [3, 8];
[left, right] = [right, left];
console.log(left);
console.log(right);

Python

left, right = (3, 8)
left, right = right, left
print(left)
print(right)

What changes

Both programs print 8 and then 3. Python unpacking assigns one sequence item to each target. For ordinary unpacking, the item count must match the target count; too many or too few items raise ValueError. This differs from JavaScript destructuring that can leave an unmatched target as undefined. The right side is evaluated before the assignments, which makes swapping possible without a temporary name. A tuple is an ordered sequence whose item references cannot be replaced after construction. The comma makes a tuple: (5,) contains one item, while (5) is the integer five. Tuple indexing and slicing follow the sequence rules already used with lists.

Common mistake

A tuple is not a JavaScript array that you promise not to edit. Python rejects replacing a tuple item. However, a list stored inside a tuple can still be changed; tuple immutability does not recursively freeze every object reachable from it.

Your task

Unpack a coordinate pair and build its swapped form while preserving the original tuple. Rebinding coordinate names does not alter the tuple you unpacked.

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 JavaScript Developers

Practice on your own: Online Python compiler