classification
Title: nested list value change
Type: behavior Stage:
Components: Library (Lib) Versions: Python 2.6, Python 2.5
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: pushkarparanjpe, rhettinger
Priority: normal Keywords:

Created on 2009-06-06 07:04 by pushkarparanjpe, last changed 2009-06-06 07:21 by rhettinger. This issue is now closed.

Messages (2)
msg88989 - (view) Author: Pushkar Paranjpe (pushkarparanjpe) Date: 2009-06-06 07:04
Is this a bug ?

>>> a = [[1,2],[3,4],[5,6]]
>>> a
[[1, 2], [3, 4], [5, 6]]
>>> b = a[0]
>>> b
[1, 2]
>>> b[0] = -8888
>>> b
[-8888, 2]
>>> a
[[-8888, 2], [3, 4], [5, 6]]
>>>

Created a new variable (b) which refers to an element in a list (a).
Changing the value of the new variable also reflects in the original
list. I thought the new variable is actually a new variable with its own
memory allocation and not a symbolic link to pre-existing data. is this
a bug?
Please help.
msg88991 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2009-06-06 07:21
This is correct behavior.
Try making a new *copy* of the sublist:

a = [[1,2],[3,4],[5,6]]
b = a[0][:]
b[0] = -8888
History
Date User Action Args
2009-06-06 07:21:44rhettingersetstatus: open -> closed

nosy: + rhettinger
messages: + msg88991

resolution: not a bug
2009-06-06 07:04:01pushkarparanjpecreate