Introduction

Python allows you to assign values to multiple variables in a single statement. This improves code clarity and reduces repetition. Multiple value assignment works with individual values, unpacking iterables, and assigning the same value to several variables.

1. Assigning Multiple Values to Multiple Variables

In Python, you can assign several values to corresponding variables in one line using commas on both sides of the = operator.

Syntax:

var1, var2, var3 = value1, value2, value3

Example:

x, y, z = "Apple", "Banana", "Cherry" print(x) print(y) print(z)
#output
#Apple Banana Cherry

This method assigns value1 to var1, value2 to var2, and so on.

2. Assigning the Same Value to Multiple Variables

Python lets you assign the same value to more than one variable in one line.

Syntax:

a = b = c = 10

Example:

a = b = c = "Hello" print(a) print(b) print(c)
#output
Hello Hello Hello

This assigns "Hello" to all three variables.

Be cautious when using this with mutable objects (like lists or dictionaries): all variables will reference the same object, so modifying one affects all.

3. Unpacking Collections

Python allows you to assign elements from a tuple, list, or other iterable directly into variables. This is called unpacking.

Example with a list:

fruits = ["apple", "banana", "cherry"] x, y, z = fruits print(x, y, z)
#output
apple banana cherry

This works with tuples, lists, and other iterable types.

If the number of variables on the left does not match the number of items on the right, Python raises a ValueError.

4. Common Use Cases

Swapping Variables

Multiple assignment makes swapping two variable values easier without a temporary variable.

Example:

x, y = 5, 10 x, y = y, x print(x, y)
#output
#10 5

This swaps the values of x and y cleanly.

Unpacking Function Returns

Functions that return multiple values can be directly assigned to variables.

def get_point(): return 3, 4 x, y = get_point() print(x, y)
#output
#3 4


This technique simplifies handling multiple return values