Multiple Assignment
Multiple Assignment
Multiple assignment in Python allows you to assign multiple values to multiple variables in a single line. It's a convenient way to initialize variables or swap their values without needing multiple lines of code. There are a few different ways to perform multiple assignments in Python:
1. Multiple Variables with Multiple Values:
You can assign values to multiple variables in a single line by separating the variables and values with commas. The number of variables must match the number of values.
```python
x, y, z = 1, 2, 3
```
2. Tuple Unpacking:
You can use tuple packing and unpacking to assign multiple values to multiple variables. This is often used when returning multiple values from a function.
```python
point = (4, 5)
x, y = point
```
3. Swapping Variables:
Multiple assignment is commonly used to swap the values of two variables without using a temporary variable.
```python
a = 5
b = 10
a, b = b, a # Swaps the values of a and b
```
4. Extended Unpacking (Python 3.0 and later):
You can also use the `*` operator for extended unpacking. This allows you to capture multiple values into one variable, as well as to capture remaining values into another variable.
```python
first, *rest = 1, 2, 3, 4, 5
# first = 1
# rest = [2, 3, 4, 5]
```
Multiple assignment is a useful feature in Python that can help make your code more concise and readable, especially when dealing with operations involving multiple variables.
Comments
Post a Comment