DEV Community

Adam Lombard
Adam Lombard

Posted on • Edited on

Python: Assignment Operators

In a programming language, assignment operators are typically used to assign values to variables.

In Python, the basic assignment operator works like this:

Operator Description Example
= Assign a value to a variable x = 2

Python also has seven arithmetic assignment operators, which are a sort of shorthand for performing two operations in sequence -- 1) arithmetic between a variable operand on the left of the expression and some other value on the right, and then 2) the assigning of the result back to the original variable:

Operator Description Example Equivalent To
+= Add a value to a variable x += 2 x = x + 2
-= Subtract a value from a variable x -= 2 x = x - 2
*= Multiply a variable by a value x *= 2 x = x * 2
**= Raise a variable to the power of a value (exponentiation) x **= 2 x = x ** 2
/= Divide a variable by a value x /= 2 x = x / 2
//= Divide a variable by a value, and round down (floor division) x //= 2 x = x // 2
%= The remainder of dividing a variable by a value (modulo) x %= 2 x = x % 2

Similarly, Python also has five bitwise assignment operators. These perform bitwise operations (the subject of a future article... ) between the left operand variable and a value on the right, assigning the result back to the variable:

Operator Description Example Equivalent To
&= Bitwise AND x &= 2 x = x & 2
|= Bitwise OR x |= 2 x = x | 2
^= Bitwise XOR x ^= 2 x = x ^ 2
>>= Bitwise right shift x >>= 2 x = x >> 2
<<= Bitwise left shift x <<= 2 x = x << 2

Was this helpful? Did I save you some time?

๐Ÿซ– Buy Me A Tea! โ˜•๏ธ


Top comments (0)