-2

Simple version of my code looks like this

def update_test(testdict):
    testdict["key"]["key"] = testdict["key"]["key"] + 2
    return testdict

testlist = []
testdict = {"key": {"key": 0}}

for i in range(10**2):
    testlist.append(testdict.copy())
    
    if i % 5 == 0:
        testdict = update_test(testdict)

print(testlist)

What is strange for me is that for some reason variable testlist remember connection to variable testdict eventhough I appended just a copy of it, so as the result at the end all items in the array are the same. I found also solution where it works correctly:

def update_test(testdict):
    newdict = {"key": {"key": testdict["key"]["key"] + 2}}
    return newdict

testlist = []
testdict = {"key": {"key": 0}}

for i in range(10**2):
    testlist.append(testdict.copy())
    
    if i % 5 == 0:
        testdict = update_test(testdict)

print(testlist)

Can somebody explain what actually happen here?

Emil Haas
  • 83
  • 9

0 Answers0