Python Advance Course

Packing and Unpacking in Python

Packing and Unpacking in Python

Packing and unpacking allows Python to assign or pass multiple values easily.

It is widely used in: - APIs - Django views - Data processing - Function arguments


1. Tuple Unpacking

Tuple unpacking means assigning values from a tuple into variables.

Example:

data = (10, 20, 30)
a, b, c = data
print(a, b, c)

Output:

10 20 30

Real-world example:

user = ("John", 25, "Engineer")
name, age, profession = user
print(name, age, profession)

Common mistake:

a, b = (1, 2, 3)

Error: too many values to unpack

Fix:

a, b, c = (1, 2, 3)

Homework:

student = ("Aman", 18, "BSc")

Solution:

student = ("Aman", 18, "BSc")
name, age, course = student
print(name, age, course)

2. List Unpacking

Works same as tuples.

Example:

numbers = [1, 2, 3]
x, y, z = numbers
print(x + y + z)

Output:

6

Real-world example:

prices = [100, 200, 300]
p1, p2, p3 = prices
print(p2)

Common mistake:

a, b = [1, 2, 3, 4]

Fix:

a, b, *rest = [1, 2, 3, 4]

Homework:

data = [10, 20, 30, 40, 50]
a, b, *rest = data
print(a, b, rest)

3. Dictionary Unpacking

Uses ** for unpacking.

Example:

person = {"name": "John", "age": 30}
print({**person})

Output:

{'name': 'John', 'age': 30}

Real-world example:

default = {"theme": "light", "font": "Arial"}
user = {"theme": "dark"}
config = {**default, **user}
print(config)

Common mistake:

{person}

Fix:

{**person}

Homework:

a = {"x": 1}
b = {"y": 2}
merged = {**a, **b}
print(merged)

4. Argument Unpacking

Using *

def add(a, b, c):
    return a + b + c

nums = (1, 2, 3)
print(add(*nums))

Output:

6

Real-world example:

def order(item1, item2):
    print(item1, item2)

items = ["Pizza", "Burger"]
order(*items)

Using **

def profile(name, age):
    print(name, age)

data = {"name": "Aman", "age": 22}
profile(**data)

Common mistake:

profile(*data)

Fix:

profile(**data)

Homework:

def total(a, b, c):
    return a + b + c

values = [5, 10, 15]
print(total(*values))

Summary

Concept Symbol Meaning
Tuple unpacking a,b,c = tuple split values
List unpacking *rest flexible unpack
Dict unpacking **dict expand key-values
Argument unpacking * / ** function passing

Visual Flow

Packing: (1,2,3)

Unpacking: a,b,c = (1,2,3)

Function call: func(*args, **kwargs)


Real-world Mapping

Concept Example
Tuple unpacking database row
List unpacking cart items
Dict unpacking configuration merge
Argument unpacking API requests

Common Mistakes

  • Too many variables
  • Wrong unpack type
  • Missing * or **

Next Topics

  • Iterators
  • Generators (yield)
  • Context managers (with)
  • Decorators chaining
  • functools module
  • Async programming

Filters

No filters available for this view.

Reset All