Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Augmented assignment


The augmented assignment statement combines an operator with assignment. A common example is this:

a += 1

This is equivalent to

a = a + 1

When working with immutable objects (numbers, strings, and tuples) the idea of an augmented assignment is syntactic sugar. It allows us to write the updated variable just once. The statement a += 1 always creates a fresh new number object, and replaces the value of a with the new number object.

Any of the operators can be combined with assignment. The means that +=, -=, *=, /=, //=, %=, **=, >>=, <<=, &=,^=, and |= are all assignment operators. We can see obvious parallels between sums using +=, and products using *=.

In the case of mutable objects, this augmented assignment can take on special significance. When we look at list objects in Chapter 6, More Complex Data Types, we'll see how we can append an item to a list object. Here's a forward-looking example:

>>> some_list = [1, 1, 2, 3]

This assigns a list object...