Oct-24-2019, 02:01 PM
An important point that comes from this - as long as an object has a reference pointing to it, it is live and kept. When there are no references it is available for reuse (garbage collection). The equals sign establishes a reference to the object. So:
x = [5,6] print(x) y = x print(y) x.append(7) print(y) x = [3] print(x,y)gives output of
Output:[5, 6]
[5, 6]
[5, 6, 7]
[3] [5, 6, 7]
The append in line 5 adds a 7 to the list referenced by x. It is the same list referenced by y (the line y=x does NOT make a copy, rather adds a second reference to the same object). So, printing y shows the 7 even though you did not modify y anywhere. When you reassign x to a different object in line 7, the first list remains referenced by y and the new list is referenced by x.