Python Unpacking [Ultimate Guide]

5/5 - (1 vote)

In this article, you’ll learn about the following topics:

  • List unpacking in Python
  • Tuple unpacking in Python
  • String unpacking in Python
  • ValueError: too many values to unpack (expected k)
  • ValueError: not enough values to unpack (expected x, got y)
  • Unpacking nested list or tuple
  • Unpacking underscore
  • Unpacking asterisk

Sequence Unpacking Basics

Python allows you to assign iterables such as lists and tuples and assign them to multiple variables.

💡 Iterable unpacking or sequence unpacking is the process of assigning the elements of an iterable (e.g., tuple, list, string) to multiple variables. For it to work, you need to have enough variables to capture the number of elements in the iterable.

Python List Unpacking

List unpacking is the process of assigning k elements of a list to k different variables in a single line of code.

In the following example, you unpack the three elements in the list [1, 2, 3] into variables a, b, and c. Each variable captures one list element after the unpacking operation.

# List Unpacking
a, b, c = [1, 2, 3]

print(a)
# 1

print(b)
# 2

print(c)
# 3

ValueError: too many values to unpack (expected k)

If the list has too many values to unpack — i.e., the number of elements in the list is larger than the variables to assign them to — Python will raise a ValueError: too many values to unpack (expected k) whereas k is the number of variables on the left-hand side of the assignment operation.

This can be seen in the following code snippet:

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

'''
Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 1, in <module>
    a, b, c = [1, 2, 3, 4]
ValueError: too many values to unpack (expected 3)
'''

To resolve the ValueError: too many values to unpack (expected k), make sure that the number of elements on the right and left-hand sides of the unpacking operation is the same.

Per convention, if you don’t need to store a certain list element in a variable, you can use the “throw-away” underscore variable name _.

Here’s the same example resolved using the underscore name:

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

print(a)
# 1

print(b)
# 2

print(c)
# 4

Alternatively, you can also use the asterisk operator on the left-hand side as will be explained at the end of this article—so keep reading! 💡

ValueError: not enough values to unpack (expected x, got y)

If the iterable has too few values to unpack — i.e., the number of elements in the iterable is larger than the variables to assign them to — Python will raise a ValueError: not enough values to unpack (expected x, got y) whereas x is the number of variables on the left-hand side of the assignment operation and y is the number of elements in the iterable.

This can be seen in the following code snippet:

a, b, c, d = [1, 2, 3]

'''
Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 1, in <module>
    a, b, c, d = [1, 2, 3]
ValueError: not enough values to unpack (expected 4, got 3)
'''

To resolve the ValueError: not enough values to unpack (expected x, got y), make sure that the number of elements on the right and left-hand sides of the unpacking operation is the same.

Python Tuple Unpacking

Tuple unpacking is the process of assigning k elements of a tuple to k different variables in a single line of code.

In the following example, you unpack the three elements in the tuple (1, 2, 3) into variables a, b, and c. Each variable captures one tuple element after the unpacking operation.

# Tuple Unpacking
a, b, c = (1, 2, 3)

print(a)
# 1

print(b)
# 2

print(c)
# 3

Note that the parentheses of tuples are optional, so you can omit them to obtain the same behavior with even fewer syntax overhead as shown in the following example. 😊

# Tuple Unpacking
a, b, c = 1, 2, 3

print(a)
# 1

print(b)
# 2

print(c)
# 3

Python String Unpacking

String unpacking is the process of assigning k characters of a string to k different variables in a single line of code.

In the following example, you unpack the seven characters in the string 'finxter' into variables a, b, c, d, e, f, and g. Each variable captures one character from the string, in order, after the unpacking operation.

# String Unpacking
a, b, c, d, e, f, g = 'finxter'

print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
print(g)

'''
f
i
n
x
t
e
r
'''

Python Unpacking Nested List or Tuple

You can also unpack a nested iterable (e.g., list of lists, or tuple of tuples).

The simple case is where one variable (in our example c) captures the whole inner list (in our example [3, 4, 5]):

lst = [1, 2, [3, 4, 5]]
a, b, c = lst

print(a)
print(b)
print(c)

'''
1
2
[3, 4, 5]
'''

But how can you assign the elements of the inner list to variables as well?

This can be done by setting up a parallel structure on the left and right sides of the equation using parentheses (...) or square brackets [...].

lst = [1, 2, [3, 4, 5]]
a, b, [c, d, e] = lst

print(a)
print(b)
print(c)
print(d)
print(e)

'''
1
2
3
4
5
'''

The simple heuristic to understand what is going on here is: parallel structures!

Python Unpacking Underscore

The underscore _ in Python behaves like a normal variable name. Per convention, it is used if you don’t actually care about the value stored in it but just use it to capture all values from an iterable in a syntactically correct way.

Here’s a simple example:

lst = ['Alice', 'Bob', 'Carl']

a, _, c = lst

print(a)
print(_)
print(c)

'''
Alice
Bob
Carl
'''

Python Unpacking Asterisk

You can use the asterisk operator * on the left-hand side of the equation to unpack multiple elements into a single variable.

This way, you can overcome the ValueError: too many values to unpack when there are more values in the iterable than there are variables to capture them.

Here’s an example where we capture two elements 2 and 3 in one variable b using the asterisk operator as a prefix in *b:

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

print(a)
print(b)
print(c)

'''
1
[2, 3]
4
'''

Note: This only works in Python 3 but not in Python 2. Here’s how to check your Python version.

Python will automatically assign the values in the iterable to the variables so that the asterisked’ variable captures all remaining elements.

In the following example, the asterisked variable *a captures all the remaining values that cannot be captured by the non-asterisked variables:

*a, b, c = [1, 2, 3, 4, 5]

print(a)
print(b)
print(c)

'''
[1, 2, 3]
4
5
'''

No matter how many elements are captured by the asterisked variable, they will always be stored as a list (even if a single variable would be enough):

first, *_, last = ['Alice', 'Bob', 'Carl']

print(first)
print(_)
print(last)

'''
Alice
['Bob']
Carl
'''

However, you cannot use multiple asterisk operators in the same expression or Python wouldn’t know which iterable elements to assign to which variables.

The following screenshot shows how Python doesn’t compile with the warning “SyntaxError: multiple starred expressions in assignment”.

If you’re completely uninterested in all but a couple of elements of a large list, you can combine the throw-away underscore operator _ with the asterisk operator * like so *_. Using this approach, the underscore will capture all the unnecessary elements from the iterable.

This can be seen in the following example:

How to Capture First and Last Element of an Iterable in Variable [Example]

Here’s an example of this:

first, *_, last = list(range(100))

print(first, last)
# 0 99

All list elements 1 to 98 (included) are now stored in the throw-away variable _.

Python assigns an empty list to the asterisked variable if no additional elements can be assigned to it because all are already assigned to other variables:

a, b, *c = [1, 2]

print(a)
print(b)
print(c)

'''
1
2
[]
'''

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!