….
🧠 Python Variables – Assign Multiple Values in One Go
Writing cleaner, shorter, and more efficient code is what Python is all about. Let’s explore how Python allows multiple value assignments to variables—an elegant feature that makes your code both powerful and readable.
✅ Assigning Multiple Values in One Line
Python allows you to assign multiple values to multiple variables in a single line of code. This is ideal for initializing multiple variables at once.
🔹 Example:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
📌 Make sure the number of variables matches the number of values, or you’ll get a ValueError
.
🟠 Assigning One Value to Multiple Variables
Need to initialize several variables with the same value? Python makes it simple.
🔹 Example:
x = y = z = "Orange"
print(x)
print(y)
print(z)
✅ All three variables will point to the same string object: "Orange"
.
🔓 Unpacking Collections (List/Tuple)
When you have a collection like a list or tuple, Python allows you to unpack values into separate variables.
🔹 Example – Unpacking a List:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
💡 This is known as sequence unpacking and works with tuples, lists, sets, and other iterables.
⚠️ Common Error to Avoid
x, y = "apple", "banana", "cherry"
# ❌ This will raise: ValueError: too many values to unpack
📌 Always ensure the number of variables equals the number of items in the iterable.
🧪 Try This in GoNimbus Editor!
Use our interactive Python playground to test assignments:
# Assign same value
a = b = c = "Python"
print(a, b, c)
# Assign different values
name, age, country = "Alice", 28, "India"
print(name, age, country)
# Unpack a list
colors = ["red", "green", "blue"]
r, g, b = colors
print(r, g, b)
💡 GoNimbus Tip:
Use multiple assignments wisely for clean code, especially when working with functions that return multiple values (e.g., x, y = get_coordinates()
).
🧩 Quick Exercise
Q: Which of the following correctly assigns "Hello World"
to three variables in one line?
A) x, y, z = 'Hello World'
B) x = y = z = 'Hello World'
C) x|y|z = 'Hello World'
✅ Correct Answer: B