Parallel Assignment and Tuples
Lesson 13 of 48 in Coddy's Python for Ruby Developers course.
Ruby multiple assignment and Python unpacking both let you swap two bindings without a temporary variable. Python also has a built-in immutable sequence type, the tuple. A comma makes a tuple; a single-element tuple needs a trailing comma. Ruby often uses arrays for the same grouped values. Tuple immutability fixes its slots, not the contents of referenced mutable objects, much like freezing a Ruby array does not recursively freeze its elements. Python fixed-length unpacking requires exactly the expected number of elements; Ruby multiple assignment can supply nil for missing values and ignore extras. Use a starred Python target to collect a remainder explicitly.
Ruby
x, y = [3]
p x
p yPython
try:
x, y = [3]
except ValueError:
print('unpack error')
x, y = 3, 8
x, y = y, x
print(x, y)Porting trap
Parentheses alone do not create a tuple. (3) is an integer expression, while (3,) is a one-element tuple.
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 Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler