Python – Unpack Tuples
1. What Does βUnpack Tupleβ Mean?
Unpacking a tuple means taking values from a tuple and putting them into separate variables.
In simple words:
π One tuple β many variables
2. Simple Tuple Unpacking
The number of variables must match the number of values.
Example
fruits = ("apple", "banana", "orange")
a, b, c = fruits
print(a)
print(b)
print(c)
3. Unpacking with Numbers
Example
numbers = (10, 20)
x, y = numbers
print(x)
print(y)
4. Using Asterisk (*) for Unpacking
The * is used to collect extra values.
Example
colors = ("red", "blue", "green", "yellow")
a, *b = colors
print(a)
print(b)
Output:
red
['blue', 'green', 'yellow']
5. Using * in Middle
Example
colors = ("red", "blue", "green", "yellow")
a, *b, c = colors
print(a)
print(b)
print(c)
6. Unpacking with Loop (Real Use Case)
Example
students = [("Amit", 20), ("Ravi", 22)]
for name, age in students:
print(name, age)
7. Unpacking Returned Values
Functions can return tuples.
Example
def get_data():
return ("Python", 3)
name, version = get_data()
print(name)
print(version)
8. Common Beginner Mistakes
β Wrong Number of Variables
a, b = (1, 2, 3)
β Error.
β Fix:
a, b, c = (1, 2, 3)
β Forgetting * for Extra Items
a, b = ("red", "blue", "green")
β Correct:
a, *b = ("red", "blue", "green")
9. Simple Practice Examples
Example 1: Unpack Student Info
student = ("Amit", 85, "Delhi")
name, marks, city = student
print(name)
print(marks)
print(city)
Example 2: First and Rest
nums = (1, 2, 3, 4)
first, *rest = nums
print(first)
print(rest)
Example 3: Swap Using Tuple Unpacking
a = 5
b = 10
a, b = b, a
print(a, b)
10. Summary (Unpack Tuples)
β Unpacking splits tuple into variables
β Number of values should match
β * collects extra values
β Very useful in loops and functions
π Perfect for Beginner eBook
This chapter is ideal for:
-
Python beginner books
-
School & college students
-
Self-learners
If you want next, I can write:
-
Tuple Methods
-
Tuple Exercises
-
Sets (easy)
-
Dictionaries (easy)
Just tell me π
