Assignments in Python
Basic Assignment
The most common form of assignment in Python uses the equal sign (=). The expression on the right side of the equal sign is evaluated, and the resulting value is assigned to the variable on the left side.
Python
x = 10
name = "Alice"
is_student = True
Multiple Assignment
Python allows assigning values to multiple variables simultaneously:
Python
a, b, c = 1, 2, 3
Augmented Assignment
Python provides augmented assignment operators for performing an operation and assigning the result back to the same variable in a concise way:
Python
x = 5
x += 3 # Equivalent to x = x + 3
print(x) # Output: 8
Other augmented assignment operators include:
- -= (subtract and assign)
- *= (multiply and assign)
- /= (divide and assign)
- //= (floor divide and assign)
- %= (modulo and assign)
- **= (exponent and assign)
Sequence Unpacking
You can unpack values from sequences (like lists, tuples) into variables:
Python
my_list = [10, 20, 30]
x, y, z = my_list
print(x, y, z) # Output: 10 20 30
Important Points
- Assignment creates a reference to an object, not a copy.
- The right side of the assignment is evaluated before the assignment takes place.
- Augmented assignment operators can improve code readability.
- Sequence unpacking is a powerful way to handle multiple values at once.
Example
Python
# Basic assignment
age = 30
# Augmented assignment
count = 5
count += 2 # Increment count by 2
# Sequence unpacking
coordinates = (3, 7)
x, y = coordinates
# Multiple assignment
a = b = c = 10
By understanding these assignment concepts, you can effectively manipulate variables and data in your Python programs.