Python @ DjangoSpin

Python: Augmented Assignments

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Augmented Assignments in Python

Augmented Assignments in Python

There are cases when you are storing the result of a binary operation into one of the operands. For example, a = a + b or a = a + 1. In such cases, the operand a is evaluated twice. Python offers an alternative, known as Augmented Assignment, in which the operand a is evaluated only once. This alternative is more efficient and offers shorthand for binary operations.

# REGULAR ASSIGNMENT
>>> x = 10
>>> x = x + 5
>>> x
15

# AUGMENTED ASSIGNMENT
>>> x = 10
>>> x += 5
>>> x
15

The operator is not limited to +, it can be either of the following binary operators: +, -, *, /, //, %, **, >>, <<, &, ^, |.


See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply