Assigning Values from Collections (Unpacking) in Python

Assigning Values from Collections (Unpacking) in Python

12. Assigning Values from Collections (Unpacking)

Python makes it super easy to extract multiple values from a list, tuple, or other iterable in a single line of code — this is known as unpacking. It’s a clean and readable way to assign values directly to variables.

Basic Example: Unpacking Lists and Tuples

# Unpacking a list
numbers = [1, 2, 3]
x, y, z = numbers
print(x, y, z)  # Output: 1 2 3

# Unpacking a tuple
person = ("Alice", 25, "Blue")
name, age, favorite_color = person
print(name, age, favorite_color)  # Output: Alice 25 Blue

Explanation:

Python automatically matches the number of variables on the left with the number of values on the right. This makes it easy to extract multiple values in one line.

  • numbers contains three elements → [1, 2, 3]
  • So Python assigns:
    1. x = 1
    2. y = 2
    3. z = 3

This helps you extract multiple items from a list, tuple, or any iterable in one elegant line.

🌍 Real-Life Application

Imagine unpacking a lunchbox 🍱 that contains a sandwich, fruit, and drink:

sandwich, fruit, drink = lunchbox

Each item in the box goes neatly into its matching variable — no confusion, no leftovers!

Using * for Flexible Unpacking

Sometimes, you may not know exactly how many elements are in your collection — or you may only care about a few of them. Python’s * (star) operator lets you capture “the rest” of the items automatically.

numbers = [1, 2, 3, 4, 5]

first, *middle, last = numbers
print(first)   # Output: 1
print(middle)  # Output: [2, 3, 4]
print(last)    # Output: 5

**🧩 Explanation:**

  • first → gets the first element or value (1)
  • last → gets the last value (5)
  • middle → captures everything in between as a list or collects eveything in between ([2, 3, 4]).

This is known as extended unpacking, and it works well with lists, tuples, or even strings.

🧪 Try It Yourself! Example 1: Ignore Some Values

You can use an underscore (_) to ignore values you don’t need:

person = ("Bob", 30, "Canada", "Engineer")

name, age, *_ = person
print(name)  # Output: Bob
print(age)   # Output: 30

Example 2: Unpack Strings

Strings are iterable, so you can unpack characters too:

letters = "ABC"
a, b, c = letters
print(a, b, c)  # Output: A B C

Your next step is to learn about Multiple Assignment in a Single Line in Python in detail.