Packing & Unpacking Tuple

  • This lesson explains how multiple values can be packed into and unpacked from tuples.

  •  What is Packing?

    Packing means storing multiple values into a single tuple variable.

    👉 When we assign multiple values separated by commas, Python automatically packs them into a tuple.

    Daily Life Example

    Packing clothes into a bag
    Different items → one bag
    Similarly: multiple values → one tuple

Basic Packing

# Packing values into a tuple
student = ("Rahul", 21, "Python")

print(student)
print(type(student))

  • Explanation

    • "Rahul", 21, "Python" are packed together

    • student becomes a tuple

Packing Without Parentheses

data = 10, 20, 30
print(data)
print(type(data))
  • Explanation

    Even without (), Python packs values into a tuple automatically.

    What is Unpacking?

    Unpacking means extracting values from a tuple into separate variables.

    Number of variables must match number of tuple elements.

    Daily Life Example

    Unpacking groceries from a bag
    One bag → items separated

Basic Unpacking

student = ("Amit", 22, "Delhi")
name, age, city = student
print(name)
print(age)
print(city)
  • Explanation

    • Tuple has 3 values

    • Assigned to 3 variables

Unpacking with Different Data

values = (100, 200)
a, b = values
print(a)
print(b)
  • Special Type: Extended Unpacking

    Used when the number of variables is different.
    We use * to collect multiple values.


numbers = (1, 2, 3, 4, 5)
a, *b, c = numbers
print(a)
print(b)
print(c)
  • Explanation

    • a gets first value → 1

    • c gets last value → 5

    • b collects remaining values → [2, 3, 4]

  • Error Case (Important)

    data = (10, 20, 30)

    a, b = data   # ❌ Error

    Reason

    Number of variables (2) ≠ number of values (3)