Member-only story

5 Essential Tuple Unpacking Techniques

Python Coding
2 min readSep 2, 2024

--

1. Basic Tuple Unpacking

person = ("John", 28, "Engineer")

name, age, profession = person

print(f"Name: {name}")
print(f"Age: {age}")
print(f"Profession: {profession}")
Name: John
Age: 28
Profession: Engineer

Explanation: This program unpacks a tuple containing personal details into individual variables.

2. Swapping Variables Using Tuple Unpacking

a = 5
b = 10

a, b = b, a

print(f"a: {a}")
print(f"b: {b}")
a: 10
b: 5

Explanation: This program swaps the values of two variables using tuple unpacking in a single line.

3. Unpacking Elements from a List of Tuples

students = [("Alice", 85), ("Bob", 90), ("Charlie", 88)]

for name, score in students:
print(f"Student: {name}, Score: {score}")
Student: Alice, Score: 85
Student: Bob, Score: 90…

--

--

Python Coding
Python Coding

Written by Python Coding

Learn python tips and tricks with code I Share your knowledge with us to help society. Python Quiz: https://www.clcoding.com/p/quiz-questions.html

No responses yet