by: Cobena Isaac

How to Assign Values from Collections in Python

How to Assign Values from Collections in Python

Python provides a feature that lets you extract multiple values from a list, tuple, or any iterable and assign them to variables in a single, clean line of code. This is called unpacking. It’s helps you to write readable and efficient Python code.

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

Python automatically matches the number of variables on the left with the number of values in the iterable on the right. This makes it easy to extract multiple values in one line. For the list [1, 2, 3], the assignment works like this:

  • 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.


Practical Application:

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

sandwich, fruit, drink = lunchbox

Each item from the lunchbox goes directly into its own named variable — organized, efficient, and with no leftovers.


Using * for Extended Unpacking

What if you don’t know exactly how many elements are in your collection, or you only need a few specific values? 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
  • first → gets the first element or value (1)
  • last → gets the last element (5)
  • middle → captures or collects everything in between as a list [2, 3, 4].

This technique, known as extended unpacking, works with lists, tuples, strings, and any iterable.


Try It Yourself :

  1. 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

# The country and profession are captured by *_ and discarded
  1. Strings are iterable, you can unpack their characters too:
letters = "ABC"
a, b, c = letters
print(a, b, c)  # Output: A B C
  1. Grab First Few, Capture the Rest
colors = ["red", "blue", "green", "yellow", "purple"]
first_color, *other_colors = colors
print(first_color)   # Output: red
print(other_colors)  # Output: ['blue', 'green', 'yellow', 'purple']

Hope this tutorial helps! Read our other tutorials to learn more.

To continue building your skills, your next step is to learn about How to Assign Multiple Variables in Python in detail.