Assign Multiple Values
In Python, you can assign multiple values to multiple variables in a single statement. This can be useful for unpacking sequences like lists or tuples, and for assigning the same value to multiple variables. In this lesson, we will cover various ways to assign multiple values in Python.
Assigning Multiple Values
You can assign multiple values to multiple variables in a single line by separating the values with commas. For example:
x, y, z = 1, 2, 3
print(x, y, z)
Output:1 2 3
Swapping Variables
You can also use multiple assignment to swap the values of variables. For example:
a, b = 1, 2
a, b = b, a
print(a, b)
Output:2 1
Assigning the Same Value
You can assign the same value to multiple variables in a single line. For example:
x = y = z = 0
print(x, y, z)
Output:0 0 0
Conclusion
Assigning multiple values in Python allows you to work efficiently with sequences and variables. By using multiple assignment, you can write concise and readable code for assigning values to variables.