Assign Multiple Values

Python allows you to assign values to multiple variables in one line. This can be done using tuple unpacking or list unpacking, which makes your code more concise and readable.

Tuple Unpacking:

Tuple unpacking is a common way to assign multiple values to variables in a single line:

Python
a, b, c = 1, 2, 3
print(a)  # Output: 1
print(b)  # Output: 2
print(c)  # Output: 3

List Unpacking:

You can also unpack lists in a similar way:

Python
x, y, z = [4, 5, 6]
print(x)  # Output: 4
print(y)  # Output: 5
print(z)  # Output: 6

Assigning the Same Value to Multiple Variables:

Python allows you to assign the same value to multiple variables in one line:

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

Swapping Values:

One practical use of multiple assignment is swapping the values of two variables without using a temporary variable:

Python
a, b = 5, 10

# Swap values
a, b = b, a

print(a)  # Output: 10
print(b)  # Output: 5

Advanced Unpacking Techniques:

You can use the underscore _ to ignore certain values during unpacking, or the wildcard * to capture the remaining values:

Python
# Ignoring certain values
a, _, c = 1, 2, 3
print(a)  # Output: 1
print(c)  # Output: 3

# Using wildcard to capture remaining values
x, *y = [1, 2, 3, 4, 5]
print(x)  # Output: 1
print(y)  # Output: [2, 3, 4, 5]

Assigning multiple values in one line is a versatile feature in Python that can simplify your code and make it more efficient.