Python Variables Assign Multiple Values
In Python, assigning values to variables is simple—but did you know you can assign multiple values to multiple variables in a single line?
This powerful feature makes your code cleaner, shorter, and easier to read. In this tutorial, we’ll explore how to assign multiple values to variables, with practical examples and best practices.
✅ What is Multiple Assignment in Python?
Multiple assignment in Python means assigning values to more than one variable in a single statement.
Syntax:
variable1, variable2, variable3 = value1, value2, value3
Each variable on the left side gets assigned the corresponding value on the right.
Example: Assigning Multiple Values
name, age, city = "Alice", 30, "New York"
print(name) # Alice
print(age) # 30
print(city) # New York
This is more concise than writing:
name = "Alice"
age = 30
city = "New York"
Swap Values Between Variables
Python allows you to swap values between two variables without using a temporary variable.
a, b = 5, 10
a, b = b, a
print("a:", a) # 10
print("b:", b) # 5
This feature is great for cleaner, more efficient swapping.
Assigning One Value to Multiple Variables
You can also assign the same value to multiple variables in one line.
x = y = z = 100
print(x) # 100
print(y) # 100
print(z) # 100
This is useful when initializing several variables with a default value.
⚠️ Mismatched Values and Variables
Make sure the number of variables matches the number of values, or Python will raise an error.
# This will raise an error:
a, b = 1, 2, 3
# ValueError: too many values to unpack (expected 2)
To handle flexible data, you can use the *
operator (called extended unpacking):
a, *b = 1, 2, 3, 4
print(a) # 1
print(b) # [2, 3, 4]
✨ Real-world Example
Here’s how multiple assignment can simplify real-world code:
product, price, stock = "Laptop", 999.99, 20
print(f"Product: {product}, Price: ${price}, In Stock: {stock} units")
Conclusion
Python’s ability to assign multiple values to variables in a single line helps write cleaner, more efficient code. It reduces repetition, simplifies swapping, and supports readable data unpacking.
Key Takeaways:
- Use
a, b = 1, 2
for multiple assignments. - Use
a, b = b, a
to swap values. - Use
x = y = z = value
to assign the same value. - Ensure variable count matches value count—or use
*
for flexible unpacking.