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:
Example:
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:
Example:
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:
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:
This swaps the values of x and y cleanly.
Unpacking Function Returns
Functions that return multiple values can be directly assigned to variables.
This technique simplifies handling multiple return values