Python Variables :Assign Multiple Values

In Python, you can assign multiple values to multiple variables in a single line. This is known as multiple assignment or tuple unpacking. Python allows assigning values in several ways depending on how many variables you want to assign and how you structure the values.

1. Assigning Multiple Values to Multiple Variables

You can assign values to several variables simultaneously by separating both the variables and the values with commas.

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

In this case:

  • a is assigned the value 1
  • b is assigned the value 2
  • c is assigned the value 3

2. Assigning the Same Value to Multiple Variables

You can also assign the same value to multiple variables in one line:

x = y = z = 100
print(x)  # Output: 100
print(y)  # Output: 100
print(z)  # Output: 100

Here, the value 100 is assigned to all three variables x, y, and z.

3. Unpacking a Sequence (Lists, Tuples)

Python allows you to unpack elements from a sequence (like a list or a tuple) and assign them to variables.

Example with a tuple:

values = (10, 20, 30)
x, y, z = values
print(x)  # Output: 10
print(y)  # Output: 20
print(z)  # Output: 30

Example with a list:

values = [5, 15, 25]
a, b, c = values
print(a)  # Output: 5
print(b)  # Output: 15
print(c)  # Output: 25

4. Using * for Variable-Length Unpacking

You can use the * symbol to capture remaining values during unpacking, assigning them to a list.

Example:

a, *b, c = 1, 2, 3, 4, 5
print(a)  # Output: 1
print(b)  # Output: [2, 3, 4]
print(c)  # Output: 5

In this case:

  • a is assigned the first value 1
  • b captures the middle values [2, 3, 4] as a list
  • c is assigned the last value 5

5. Swapping Variables Using Multiple Assignment

You can swap values between two variables without needing a temporary variable.

x, y = 10, 20
x, y = y, x
print(x)  # Output: 20
print(y)  # Output: 10

6. Assigning Values Using Expressions

You can also assign the result of expressions to multiple variables:

a, b = 5 + 2, 3 * 4
print(a)  # Output: 7
print(b)  # Output: 12

This flexibility makes Python variable assignment very powerful and concise.

Leave a Reply 0

Your email address will not be published. Required fields are marked *