in Python

in Python

Lesson 13. Multiple Assignment in a Single Line (Chained Assignment)

In Python, you can assign the same value to multiple variables in a single line using chained assignment. This is a clean and concise way to initialize several variables with a common starting value — especially useful in setup or configuration steps.

Example: Assigning the Same Value

x = y = z = 0

print(x, y, z)  # Output: 0 0 0

Explanation:

  • The value 0 is assigned to all three variables: x, y, and z.
  • Python evaluates the expression from right to left:
    1. It starts with z = 0
    1. Then assigns that same value to y
    2. Finally assigns it to x

All three variables now reference the same value.

When to Use It: his approach is helpful when:

  • You want to initialize multiple variables before using them.
  • You’re setting up default values.
  • You want to simplify setup code.

For example:

# Initialize variables before use
count = total = average = 0

print(count, total, average)  # Output: 0 0 0

⚠️ Be Careful with Mutable Objects

If you use this approach with mutable objects (like lists or dictionaries), all variables will point to the same object, not separate copies.

Let’s see what that means :

# Caution: All three variables share the same list!
a = b = c = [1, 2, 3]

a.append(4)
print(b)  # Output: [1, 2, 3, 4]
print(c)  # Output: [1, 2, 3, 4]

Explanation:

  • Since lists are mutable, modifying one affects all others.
  • a, b, and c all refer to the same list object in memory.

✅ Tip: When you need separate lists, use this approach instead:

a, b, c = [1, 2, 3], [1, 2, 3], [1, 2, 3]

Now each variable holds its own independent copy

Try It Yourself

1️⃣ Assign the same value to multiple variables:

x = y = z = "Python"
print(x, y, z)

2️⃣ Try to modify one of them:

x = "JavaScript"
print(y)  # Will it change?

3️⃣ Now try with a mutable object:

list1 = list2 = []
list1.append("Hello")
print(list2)  # What happens?

You now understand how to assign values from collections in Python. Your next step is to learn about Variable Scope in Python in detail.