> ## Documentation Index
> Fetch the complete documentation index at: https://fastapi2day.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Packing & Unpacking in Python: Starred Expressions

> Master Python packing and unpacking — tuple packing, starred expressions, dictionary merging, and clean loop iteration patterns.

Packing and unpacking are two of Python's most expressive convenience features. **Packing** lets you bundle multiple values into a single tuple in one assignment, while **unpacking** lets you extract values from any iterable — tuple, list, string, or dictionary — directly into named variables on a single line. Together, these features make your code cleaner, reduce intermediate variables, and enable elegant patterns in loops and function signatures.

## Tuple Packing

When you assign multiple values to a single variable without brackets, Python automatically groups them into a **tuple**:

```python theme={null}
person = "Alice", 25, "Engineer"

print(person)        # ('Alice', 25, 'Engineer')
print(type(person))  # <class 'tuple'>
```

No parentheses are required — the commas do the packing.

## Basic Unpacking

Unpacking is the reverse: Python extracts elements from a collection and assigns them to individual variables in one step:

```python theme={null}
person = ("Alice", 25, "Engineer")

name, age, profession = person

print(name)        # Alice
print(age)         # 25
print(profession)  # Engineer
```

<Warning>
  The number of variables on the left **must exactly match** the number of elements on the right. A mismatch raises a `ValueError`.

  ```python theme={null}
  numbers = (1, 2, 3)
  a, b, c, d = numbers   # ValueError: not enough values to unpack
  x, y = numbers         # ValueError: too many values to unpack
  ```
</Warning>

## Extended Unpacking with `*`

When you only care about specific elements and want to capture the rest as a list, prefix one variable with `*` (a starred expression):

```python theme={null}
numbers = [1, 2, 3, 4, 5]

first, *rest = numbers
print(first)   # 1
print(rest)    # [2, 3, 4, 5]
```

You can place the starred variable anywhere — at the start, end, or middle:

```python theme={null}
# Capture the last element, pack the rest
*body, last = [10, 20, 30, 40]
print(body)   # [10, 20, 30]
print(last)   # 40

# Capture first and last, pack the middle
first, *middle, last = "Python"
print(first)    # P
print(middle)   # ['y', 't', 'h', 'o']
print(last)     # n
```

<Note>
  You can use only **one** starred expression per assignment. Two starred variables in the same statement causes a `SyntaxError` because Python cannot determine where one group ends and the other begins.
</Note>

## Dictionary Unpacking with `**`

For dictionaries, the double-star `**` operator unpacks key-value pairs. This is most commonly used to merge dictionaries:

```python theme={null}
default_settings = {"theme": "light", "notifications": True}
user_settings    = {"theme": "dark", "font_size": 14}

merged = {**default_settings, **user_settings}
print(merged)
# {'theme': 'dark', 'notifications': True, 'font_size': 14}
```

Keys from later dictionaries overwrite those from earlier ones, making this pattern great for applying user preferences on top of defaults.

## Unpacking in Loops

Unpacking shines in loops, turning tuple-heavy iterations into readable, named variables.

### Iterating Over a List of Tuples

```python theme={null}
pairs = [(1, "one"), (2, "two"), (3, "three")]

for number, name in pairs:
    print(f"{number} is spelled {name}")
# 1 is spelled one
# 2 is spelled two
# 3 is spelled three
```

### Using `enumerate()`

`enumerate()` yields `(index, item)` pairs — perfect for unpacking:

```python theme={null}
fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")
# Index 0: apple
# Index 1: banana
# Index 2: cherry
```

### Iterating Over Dictionary Items

```python theme={null}
ages = {"Alice": 25, "Bob": 30}

for name, age in ages.items():
    print(f"{name} is {age} years old")
# Alice is 25 years old
# Bob is 30 years old
```

## Common Errors and Fixes

<AccordionGroup>
  <Accordion title="ValueError: too many values to unpack">
    The iterable has more elements than you have variables.

    ```python theme={null}
    # Wrong
    a, b = (1, 2, 3)   # ValueError

    # Fix: capture the remainder with *
    a, b, *rest = (1, 2, 3)
    print(a, b, rest)  # 1 2 [3]
    ```
  </Accordion>

  <Accordion title="ValueError: not enough values to unpack">
    You have more target variables than elements in the iterable.

    ```python theme={null}
    # Wrong
    a, b, c = (1, 2)   # ValueError

    # Fix: provide the right number of variables
    a, b = (1, 2)
    ```
  </Accordion>

  <Accordion title="SyntaxError: multiple starred expressions">
    Python allows only one `*` variable per assignment statement.

    ```python theme={null}
    # Wrong
    *a, b, *c = [1, 2, 3, 4]   # SyntaxError

    # Fix: use only one starred target
    *a, b = [1, 2, 3, 4]
    print(a, b)  # [1, 2, 3] 4
    ```
  </Accordion>
</AccordionGroup>
