Why does changing 1 list affect the other?

Miki Tebeka mikit at zoran.co.il
Thu Nov 6 01:50:02 EST 2003


Hello,

> why does altering one list affect the other list ? it is driving me
> insane!
In Python everything is a reference (pointer in C/C++ terms). When you
do list1 = list2 then list1 and list2 point to the same list object.
Change one and the other will see it.
If you want a copy you can either use the copy module or slicing
>>> list1 = [1,2,3]
>>> list2 = list1[:] # Create a shallow copy
>>> list1[0] = "What's up doc?"
>>> list2[0]
1
>>> list1[0]
"What's up doc?"
>>> 
Do read the tutorial (http://www.python.org/doc/current/tut/tut.html)
it does a very good job at explaining thinks like that.

HTH.
Miki




More information about the Python-list mailing list