Augmented assignments (+=, -=, etc.) in Python (8/100 Days of Python)

Martin Mirakyan
2 min readJan 9, 2023

--

Day 8 of the “100 Days of Python” blog post series covering augmented/compound assignments

In Python, you can use shorthands to perform arithmetic operations and assign the result to a variable at the same time. This can be a convenient way to write code and can save you some typing:

x = 10
y = 5

# Shorthand for x = x + y
x += y # x is now 15

# Shorthand for x = x - y
x -= y # x is now 10

# Shorthand for x = x * y
x *= y # x is now 50

# Shorthand for x = x / y
x /= y # x is now 10.0

# Shorthand for x = x % y
x %= y # x is now 0

These shorthands can be used with any arithmetic operator (+, -, *, /, %, etc.). They can also be used with multiple variables.

The list of available augmented/compound assignments in Python

It’s important to note that these shorthands only work with variables. You cannot use them to perform arithmetic operations on literal values. For example, the following code would produce an error:

x = 10
y = 5
z = 2

# Shorthand for x = x + y + z
x += y + z # x is now 17

# This would produce an error
10 += 5

In literature, these types of operations are often referred to as “augmented assignments” or “compound assignments”. They are called “augmented” because they augment the value of a variable by performing an operation on it, and “compound” because they combine an operation with an assignment.

What’s next?

--

--

Martin Mirakyan
Martin Mirakyan

Written by Martin Mirakyan

Software Engineer | Machine Learning | Founder of Profound Academy (https://profound.academy)

No responses yet