Unpacking in Python: How to Assign List and Tuple Elements to Variables

When handling lists or tuples in Python, you often want to extract their elements into individual variables. For example, handling coordinate data usually involves accessing indices like this:

point = (100.5, 35.2)

# Normal index reference
lat = point[0]
lon = point[1]

This method is reliable, but the code becomes verbose as the number of elements increases. Python has a powerful feature called “Unpacking” that expands elements of a sequence (like a list or tuple) and assigns them to multiple variables at once.

This article explains the basic usage of unpacking and points to be aware of.


目次

1. Basic Unpacking

The syntax for unpacking is very simple. On the left side of the assignment operator (=), list the variable names separated by commas. The number of variables must match the number of elements in the sequence.

# List with 3 elements
user_profile = ["Tanaka", 45, "Tokyo"]

# Unpack into 3 variables
name, age, city = user_profile

print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")

Output:

Name: Tanaka
Age: 45
City: Tokyo

user_profile[0] is automatically assigned to name, user_profile[1] to age, and user_profile[2] to city. This feature works exactly the same way with tuples.


2. Caution: Matching the Number of Variables (ValueError)

The basic rule of unpacking is that the number of variables on the left must strictly match the number of elements in the sequence on the right. If they do not match, a ValueError occurs, and the program stops.

Error Case 1: Too few variables (too many values to unpack)

This happens when there are not enough variables on the left to hold all the elements on the right.

# List with 3 elements
rgb_color = [255, 0, 128]

# Trying to receive with 2 variables
# r, g = rgb_color
# ValueError: too many values to unpack (expected 2)

Python assigned 255 to r and 0 to g, but errored because there was no variable left for 128.

Error Case 2: Too many variables (not enough values to unpack)

This happens when there are too many variables on the left compared to the elements on the right.

# List with 3 elements
rgb_color = [255, 0, 128]

# Trying to receive with 4 variables
# r, g, b, alpha = rgb_color
# ValueError: not enough values to unpack (expected 4, got 3)

It assigned values to r, g, and b, but errored because there was no 4th element for alpha.


3. Flexible Unpacking using Asterisk (*)

To avoid the ValueError mentioned above and perform more flexible unpacking, you can use the asterisk (*). A variable with * attached collects the remaining elements as a list.

# Log containing multiple pieces of data
log_data = ["2025-11-14", "10:30:05", "ERROR", "Auth Failed", "User: admin"]

# Store the first two normally, and the rest in *details
date, time, *details = log_data

print(f"Date: {date}")
print(f"Time: {time}")
print(f"Details (List): {details}")

Output:

Date: 2025-11-14
Time: 10:30:05
Details (List): ['ERROR', 'Auth Failed', 'User: admin']

You can also place the * at the beginning or in the middle.

# When you only need the first and last elements
scores = [90, 85, 88, 76, 92]
first, *middle_scores, last = scores

print(f"First Score: {first}")
print(f"Middle Scores: {middle_scores}")
print(f"Last Score: {last}")

Output:

Plaintext

First Score: 90
Middle Scores: [85, 88, 76]
Last Score: 92

Summary

  • Unpacking (a, b = [1, 2]) is a feature to assign list or tuple elements to multiple variables at once.
  • Basically, the number of variables on the left must match the number of elements on the right. A mismatch causes a ValueError.
  • Adding * (asterisk) to a variable name allows for flexible unpacking by collecting the remaining elements into a list.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次