Tuples and Destructuring
Lesson 13 of 48 in Coddy's Python for Rust Developers course.
Python tuples group positional values and support unpacking into names. x, y = point requires two elements; x, y = y, x evaluates the right side before either assignment. Like Rust, a one-element tuple needs a comma. A Python tuple cannot replace its slots, but an object referenced by a slot can still mutate. Rust tuple destructuring follows each component's Copy or move behavior. Python unpacking binds existing element objects, with no move or borrow checker involved.
Rust excerpt inside main
let point = (3, 8);
let (x, y) = point;
let (x, y) = (y, x);
println!("{} {}", x, y);
println!("{:?}", point);Python
point = (3, 8)
x, y = point
x, y = y, x
print(x, y)
print(point)Porting trap
An immutable Python tuple is not a deep freeze. A list inside a tuple remains mutable, and generally makes the tuple unsuitable as a dictionary key.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
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 Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler