This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Modifying a list/dict effects all variables sharing that address
Type: behavior Stage: resolved
Components: Versions: Python 3.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: 64andy, r.david.murray
Priority: normal Keywords:

Created on 2018-01-29 13:57 by 64andy, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (2)
msg311135 - (view) Author: 64andy (64andy) Date: 2018-01-29 13:57
If multiple lists/dictionaries are in the same memory address (usually caused by var1 = var2), then altering one will effect every variable in that address.
The ways I've found to achieve this are:
>>> my_list[2] = "Spam"
>>> my_list += "9"
>>> my_list.insert(4, "Hello")
>>> dictvar.update({"Three": "Four"})

This was achieved using Python 3.6.4 32-bit and 3.6.3 64-bit (CPython), and happened in both IDLE and python.exe

List Example code:
x = ['a','b','c']
y = x #Now y and x share a memory address, because CPython does that
print(f"Sanity test - x and y share the same address = {x is y}")

y[1] = '123'
y += ["Foo"]
y.insert(-1, "Eleven")

#x's Expected Value: ['a','b','c']
print(x) #Actual Value
msg311140 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2018-01-29 14:15
Yep, that's the way Python works.  You are modifying the same object through different names.  Remember that in Python it is the objects that matter (which are identified in CPython via their memory address, but that's an implementation detail) and names are just handy references to those objects.  There can be any number of names that reference a single object.
History
Date User Action Args
2022-04-11 14:58:57adminsetgithub: 76893
2018-01-29 14:15:53r.david.murraysetstatus: open -> closed

nosy: + r.david.murray
messages: + msg311140

resolution: not a bug
stage: resolved
2018-01-29 13:57:4564andycreate