Iterable Unpacking in Python
Buy Me a Coffee☕ *My post explains variable assignment in Python. You can unpack the iterable which has zero or more values to one or more variables as shown below: *The number of variables must match the number of values unless a variable uses *. v1, v2, v3 = [0, 1, 2] 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) *The one or more values with one or more commas(,) are a tuple. v1, v2, v3 = [0, 1, 2] v1, v2, v3 = range(0, 3) v1, v2, v3 = 0, 1, 2 # Tuple v1, v2, v3 = (0, 1, 2) print(v1, v2, v3) # 0 1 2 *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

*My post explains variable assignment in Python.
You can unpack the iterable which has zero or more values to one or more variables as shown below:
*The number of variables must match the number of values unless a variable uses *
.
v1, v2, v3 = [0, 1, 2]
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)
*The one or more values with one or more commas(,
) are a tuple.
v1, v2, v3 = [0, 1, 2]
v1, v2, v3 = range(0, 3)
v1, v2, v3 = 0, 1, 2 # Tuple
v1, v2, v3 = (0, 1, 2)
print(v1, v2, v3) # 0 1 2
*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