Augmented Assignments in Python

How augmented assignments work with mutable objects

When augmented assignment expressions are used, the most optimal operation will be automatically picked up. This means that for specific object types supporting in-place modifications, then an in-place operation will be applied since it is faster than first creating a copy and then the assignment. If you want to add an item to a list, is typically faster to use the append() method rather than using concatenation:

>>> my_lst = [1, 2, 3]>>> my_lst.append(4) # This is faster 
>>> my_lst = my_lst + [4] # This is slower

And since in-place operations are faster, they will automatically be chosen in augmented assignments. To make it clear how these expressions work with mutable object types let’s consider the example below.

If we use concatenation, then a new list object will be created. This means that if another name is sharing the same reference, it will remain unaffected by any future updates in the new object list:

>>> lst_1 = [1, 2, 3]>>> lst_2 = lst_1
>>> lst_1 = lst_1 + [4, 5]>>> lst_1
[1, 2, 3, 4, 5]>>> lst_2
[1, 2, 3]

Now if we use augmented assignment expression, which means that instead of concatenation the expression will use extend() method to perform this update, then we will also affect all other names holding the shared reference:

>>> lst_1 = [1, 2, 3]>>> lst_2 = lst_1
>>> lst2 += [4, 5]>>> lst_1
[1, 2, 3, 4, 5]>>> lst_2
[1, 2, 3, 4, 5]

Leave a Reply

Your email address will not be published.

  ⁄  one  =  3