Menu
CoddyTech

Tuples and Exact Unpacking

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

Python tuples are immutable ordered sequences, useful for grouped return values. R often returns a list or named list for that purpose. Python unpacking binds several targets from an iterable and, without a starred target, requires an exact element count. It is not the same as R vector recycling. A one-element Python tuple needs a comma, while parentheses alone only group an expression. Tuple slots cannot be replaced, but a mutable object referenced by a slot can still change. Parallel assignment evaluates the right-hand values before rebinding targets, so swapping two names is direct.

R

point <- list(3, 8)
x <- point[[1]]
y <- point[[2]]
temp <- x
x <- y
y <- temp
cat(x, y, "\n")

Python

try:
    x, y = [3]
except ValueError:
    print('unpack error')
x, y = 3, 8
x, y = y, x
print(x, y)

Porting trap

Do not expect Python unpacking to recycle a short vector or fill missing positions. Catch or prevent a mismatched length instead.

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

Practice on your own: Online Python compiler