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
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler