Menu
CoddyTech

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 y

Python

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

Practice on your own: Online Python compiler