Corey
by Corey
~1 min read

Categories

  • articles

Tags

  • Python

Shared Reference is an extremely common trick in python programming language, which means that a single object can be able to be referenced by multiple variables.

In Fig 1, L1 is an object of a list. The assignment statement L2 = L1 enables L2 to share the memory space of L1, it will turn up that L1 and L2 share the same memory space. In other words, L2 will change simultaneously with L1.

image
Fig 1: Shared Reference.
image
Fig 2: Make a copy of variable instead of shared reference.

When next time we want to use an assignment in python, think carefully if we really want shared reference, or just a copy.

Plus, thank Philip Guo for his visualization tool.