Search Here

Python Variables – Assign Multiple Values

In Python, you can assign multiple values to multiple variables in a single line of code. This is called unpacking. Here is an example of how to assign multiple values to multiple variables:

x, y, z = 1, 2, 3
print(x)  # Output: 1
print(y)  # Output: 2
print(z)  # Output: 3

You can also use this feature to swap the values of two variables. For example:

a = 5
b = 10

a, b = b, a
print(a)  # Output: 10
print(b)  # Output: 5

Note that the number of variables on the left side of the assignment operator must match the number of values on the right side. If there is a mismatch, you will get a ValueError exception.

# This will cause a ValueError
x, y = 1, 2, 3

Leave a Comment