Why does changing 1 list affect the other?

Roy Smith roy at panix.com
Wed Nov 5 23:05:30 EST 2003


 oom <oom at xxnospamxx.ps.gen.nz> wrote:

> I am a bit of a newbie when it comes to python, when working with
> lists today I noticed some very odd behaviour, any suggestions
> welcome:
> 
> Python 2.2.3 (#1, Nov  6 2003, 14:12:38) 
> [GCC 3.3.2 20031022 (Gentoo Linux 3.3.2-r2, propolice)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> firstlist=['item1','item2','item2']
> >>> secondlist=firstlist
> >>> print (firstlist,secondlist)
> (['item1', 'item2', 'item2'], ['item1', 'item2', 'item2'])
> >>> firstlist[0]='strangeness'
> >>> print (firstlist,secondlist)
> (['strangeness', 'item2', 'item2'], ['strangeness', 'item2', 'item2'])
> >>> 
> 
> why does altering one list affect the other list ? it is driving me
> insane!
> 

Because when you say secondlist = firstlist, you're not making a copy of 
the list, you're just making another reference to the existing list 
object.  If you're used to C/C++, think of it as passing a pointer 
around.

If you really wanted to make a new list, you should look at the copy 
module (specifically copy.deepcopy).  Or, somewhat simplier, you could 
have just said secondlist = list (firstlist), which creates a new one 
(kind of like a copy constructor might do in C++).




More information about the Python-list mailing list