DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on

Iterable unpacking in Python variable assignment

Buy Me a Coffee

*Memos:

  • My post explains variable assignment.
  • My post explains * for iterable unpacking in variable assignment.
  • My post explains * for iterable unpacking in function.
  • My post explains ** for dictionary unpacking.
  • My post explains *args and **kwargs in function.

You can unpack the iterable which has zero or more values to one or more variables as shown below:

*Memos:

  • A set of the one or more variables with one or more commas(,) in a variable assignment is an iterable unpacking so v1 = and v1, = are different.
  • The number of variables must match the number of values unless a *variable is used.
  • The one or more values with one or more commas(,) are a tuple.
v1, v2, v3 = [0, 1, 2]
v1, v2, v3 = 0, 1, 2 # Tuple
v1, v2, v3 = (0, 1, 2)
# No error

v1, v2, v3 = [0, 1]
# ValueError: not enough values to unpack (expected 3, got 2)

v1, v2, v3 = [0, 1, 2, 3]
# ValueError: too many values to unpack (expected 3)
v1 = [0, 1, 2]
# No error

v1, = [0, 1, 2]
# ValueError: too many values to unpack (expected 1)

*Again, a set of the one or more variables with one or more commas(,) in a variable assignment is an iterable unpacking.

v1, = [5]
v1, = 5, # Tuple
v1, = (5,)

v1, = 5
# TypeError: cannot unpack non-iterable int object

v1, = [5, 10]
# ValueError: too many values to unpack (expected 1)

v1, = []
# ValueError: not enough values to unpack (expected 1, got 0)

, = []
# SyntaxError: invalid syntax

_, = []
# ValueError: not enough values to unpack (expected 1, got 0)
v1, v2, v3 = [0, 1, 2]
v1, v2, v3 = 0, 1, 2 # Tuple
v1, v2, v3 = (0, 1, 2)
v1, v2, v3 = range(3)

print(v1, v2, v3) # 0 1 2
v1 = [0, 1, 2]

print(v1) # [0, 1, 2]
v1, = [5]
v1, = 5, # Tuple
v1, = (5,)
v1, = range(5, 6)

print(v1) 5

*By default, only keys are assigned to variables from a dictrionary same as using keys().

v1, v2, v3 = {"name":"John", "age":36, "gender":"Male"}
v1, v2, v3 = {"name":"John", "age":36, "gender":"Male"}.keys()

print(v1, v2, v3) # name age gender

*values() can get only the values from a dictionary.

v1, v2, v3 = {"name":"John", "age":36, "gender":"Male"}.values()

print(v1, v2, v3) # John 36 Male

*items() can get both the keys and values from a dictionary.

v1, v2, v3 = {"name":"John", "age":36, "gender":"Male"}.items()

print(v1, v2, v3)
# ('name', 'John') ('age', 36) ('gender', 'Male')

print(v1[0], v1[1], v2[0], v2[1], v3[0], v3[1])
# name John age 36 gender Male
v1, v2, v3, v4, v5 = "Hello"

print(v1, v2, v3, v4, v5) # H e l l o

Top comments (0)