Understand Python objects
Python copy visualizer: references and lists
Why can a change made through b also be visible through a? Follow references between variables and lists, then compare assignment, shallow copying and deep copying.
In this Python copy visualizer, choose one of the three example buttons, then use Next step just below the result. Each step brings together the Python instruction, its explanation and the values of a and b before and after. The ? buttons provide help; expand the panels below to see the reference diagram and the full code.
Free, with no registration. The displayed states come from verified Python executions. The controls move through these prepared examples; they do not execute arbitrary code.
Understand Python copy behaviour and references
A Python variable is a name bound to an object. A reference gives access to that object. Each arrow in the diagram connects a name or list item to the list it refers to.
Assignment with b = a
Both names refer to the same list. Assignment does not create a copy. Changes to a nested list, or an append to the outer list, are visible through both names.
A shallow copy with a.copy()
The outer list is new, but its items can still refer to the same objects. Here, the nested lists are shared: changing their contents also affects what you see through a.
A deep copy with deepcopy(a)
In this example, b gets a new outer list and new nested lists. Their values are initially equal to those in a, but their references are distinct. Integers are not drawn as separate objects.
The values 23, 19 and 24 come from the first three rows of the Hours_Studied column in Student Performance Factors. They are grouped into two nested lists to explore references. The examples do not modify the source file. Source of the values: Student Performance Factors
What the visualizer shows
L1, L2… identify lists in the diagram; they are not actual memory addresses. The is operator compares object identity, whereas == compares their values here. Moving backwards displays an earlier state of the demonstration. The diagram covers these lists of numbers; it does not describe every possible deepcopy behaviour for custom objects.
Visualizer preview
