Menu
CoddyTech

Pair and Tuple Unpacking

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

Kotlin destructuring uses component functions, such as Pair.component1 and component2. Python unpacks an iterable into names and uses tuples for positional grouping. Tuple slots cannot be replaced, though nested mutable objects can change. A one-item tuple requires a comma. Python simultaneous assignment can swap bindings without a temporary variable; a Kotlin Pair is not a mutable two-slot list either.

Kotlin

fun main() {
    val point = 3 to 8
    val (x, y) = point
    println("$y $x")
}

Python

point = (3, 8)
x, y = point
x, y = y, x
print(x, y)

Porting trap

Python tuple unpacking depends on iterable values, not generated componentN methods. Two names require two values unless a starred target collects the rest.

Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.

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

Practice on your own: Online Python compiler