Python - Multiple-target assignment and shared references

Introduction

In multiple-target assignment there is one object which is shared by all three variables.

This behavior is fine for immutable types.

Demo

a = b = 0 
b = b + 1 
print( a, b )

Result

In case of mutable object such as a list or dictionary:

Demo

a = b = [] 
b.append(42) 
print( a, b )

Result

Here, because a and b reference the same object, appending to it in place through b will impact a as well.

To avoid the issue, initialize mutable objects in separate statements instead:

Demo

a = [] 
b = []                 # a and b do not share the same object 
b.append(42) #  ww w  .java 2s.com
print( a, b )

Result

A tuple assignment like the following has the same effect-by running two list expressions, it creates two distinct objects:

a, b = [], []          # a and b do not share the same object 

Related Topic