by: Cobena Isaac

How to Assign Multiple Variables in Python

How to Assign Multiple Variables in Python

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, which is especially useful during setup or configuration steps.

Basic Chained Assignment

x = y = z = 0

print(x, y, z)  # Output: 0 0 0
  • 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
    2. Then assigns that same value to y
    3. Finally assigns it to x

All three variables now reference the same value in memory.

When to Use Chained Assignment

This approach is ideal when:

  • Initializing multiple related variables before using them
  • Setting up default values for configuration
  • Simplifying setup code for counters or flags

Practical Example:

# Initialize tracking variables
count = total = average = 0

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

Be careful with mutable objects

When using chained assignment with mutable objects (like lists, dictionaries, or sets), all variables reference the same object, not independent or seperate copies.

Let’s see what that means :

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

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

What Happened:

  • Since lists are mutable, modifying one variable affects all others
  • a, b, and c all point 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


Safe Alternative for Mutable Objects

When you need independent copies of mutable objects, use separate assignments:

# Each variable gets its own independent list
a, b, c = [1, 2, 3], [1, 2, 3], [1, 2, 3]

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

Try It Yourself

1️⃣ Assign the same string value:

x = y = z = "Python"
print(x, y, z)  # Output: Python Python Python

2️⃣ Modify one string variable:

x = "JavaScript"
print(y)  # Output: Python (strings are immutable, so y remains unchanged)

3️⃣ Experiment with mutable objects:

list1 = list2 = []
list1.append("Hello")
print(list2)  # Output: ['Hello'] - both variables share the same list!

Hope you enjoyed reading this tutorial! Read our other tutorials to learn more.

To continue building your skills, your next step is to learn about Python Variable Scope to discover where your variables can be accessed in your code.