0
0
PythonHow-ToBeginner · 3 min read

How to Declare Multiple Variables in Python: Simple Syntax and Examples

In Python, you can declare multiple variables in one line by separating them with commas, like a, b, c = 1, 2, 3. You can also assign the same value to multiple variables using a = b = c = 0.
📐

Syntax

You can declare multiple variables in Python in two main ways:

  • Separate assignment: Assign different values to multiple variables in one line using commas.
  • Same value assignment: Assign the same value to multiple variables in one line.
python
a, b, c = 1, 2, 3
x = y = z = 0
💻

Example

This example shows how to declare multiple variables with different values and how to assign the same value to multiple variables.

python
a, b, c = 10, 20, 30
x = y = z = 5
print(f"a={a}, b={b}, c={c}")
print(f"x={x}, y={y}, z={z}")
Output
a=10, b=20, c=30 x=5, y=5, z=5
⚠️

Common Pitfalls

One common mistake is mismatching the number of variables and values when using separate assignment, which causes an error. Another is expecting that changing one variable will change others when they share the same value assignment, but they are independent.

python
try:
    a, b = 1, 2, 3  # Too many values
except ValueError as e:
    print(f"Error: {e}")

x = y = 10
x = 20
print(f"x={x}, y={y}  # y stays 10, not changed")
Output
Error: too many values to unpack (expected 2) x=20, y=10 # y stays 10, not changed
📊

Quick Reference

SyntaxDescription
a, b, c = 1, 2, 3Assign different values to multiple variables
x = y = z = 0Assign the same value to multiple variables
a, b = b, aSwap values of two variables

Key Takeaways

Use commas to declare multiple variables with different values in one line.
Use chained assignment to give multiple variables the same value.
Ensure the number of variables matches the number of values when unpacking.
Changing one variable in chained assignment does not affect the others.
You can swap variables easily using multiple assignment syntax.