Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are lists linked in Python in a persistent way?

A variable is set. Another variable is set to the first. The first changes value. The second does not. This has been the nature of programming since the dawn of time.

>>> a = 1
>>> b = a
>>> b = b - 1
>>> b
0
>>> a
1

I then extend this to Python lists. A list is declared and appended. Another list is declared to be equal to the first. The values in the second list change. Mysteriously, the values in the first list, though not acted upon directly, also change.

>>> alist = list()
>>> blist = list()
>>> alist.append(1)
>>> alist.append(2)
>>> alist
[1, 2]
>>> blist
[]
>>> blist = alist
>>> alist.remove(1)
>>> alist
[2]
>>> blist
[2]
>>> 

Why is this?

And how do I prevent this from happening -- I want alist to be unfazed by changes to blist (immutable, if you will)?

like image 661
Todd Curry Avatar asked May 30 '26 05:05

Todd Curry


1 Answers

Python variables are actually not variables but references to objects (similar to pointers in C). There is a very good explanation of that for beginners in http://foobarnbaz.com/2012/07/08/understanding-python-variables/

One way to convince yourself about this is to try this:

a=[1,2,3]
b=a
id(a)
68617320
id(b)
68617320

id returns the memory address of the given object. Since both are the same for both lists it means that changing one affects the other, because they are, in fact, the same thing.

like image 126
hivert Avatar answered Jun 01 '26 18:06

hivert