Why does changing 1 list affect the other?

Ben Finney bignose-hates-spam at and-benfinney-does-too.id.au
Thu Nov 6 04:51:59 CET 2003


On Thu, 06 Nov 2003 16:36:08 +1300, oom wrote:
>>>> firstlist=['item1','item2','item2']

Creates a list object, containing three string objects, and binds the
name 'firstlist' to the list object.

>>>> secondlist=firstlist

Binds the name 'secondlist' to the same list object.

>>>> print (firstlist,secondlist)
> (['item1', 'item2', 'item2'], ['item1', 'item2', 'item2'])

Outputs the same list object twice, since it is bound to both
'firstlist' and 'secondlist'.

>>>> firstlist[0]='strangeness'

Alters the list object.

>>>> print (firstlist,secondlist)
> (['strangeness', 'item2', 'item2'], ['strangeness', 'item2', 'item2'])

Outputs the same list object twice, since it is bound to both
'firstlist' and 'secondlist'.

> why does altering one list affect the other list ? it is driving me
> insane!

Because there's only one list, with two different names.  This is a
result of 'secondlist = firstlist'.

What you probably want os to take a *copy* of the list object, and bind
'secondlist' to that new object.  This occurs automatically for some
types (e.g.  scalars) but not lists or dicts or other structured types.

    >>> import copy
    >>> firstlist = [ 'item1', 'item2', 'item3' ]
    >>> secondlist = copy.copy( firstlist )
    >>> print( firstlist, secondlist )
    (['item1', 'item2', 'item3'], ['item1', 'item2', 'item3'])
    >>> firstlist[0] = 'no_strangeness'
    >>> print( firstlist, secondlist )
    (['no_strangeness', 'item2', 'item3'], ['item1', 'item2', 'item3'])
    >>>

-- 
 \     "It is hard to believe that a man is telling the truth when you |
  `\   know that you would lie if you were in his place."  -- Henry L. |
_o__)                                                          Mencken |
Ben Finney <http://bignose.squidly.org/>




More information about the Python-list mailing list