I have the following code snippet. I wanted to only update the list stored inside the variable test_list
but not the original addStartAndEnd
list. But every time I modify the test_list
, surprisingly the original addStartAndEnd
list gets updated and reflects the change!
My question is, I didn't do anything with the original addStartAndEnd
list. I just fetched the last item of this list, stored it inside test_list
and tried to modify it. So how is the addStartAndEnd
list getting updated? Is this how Python functions such that every time the reference it points to gets updated it automatically modifies itself? What's the trick? Please assist.
Attached is the code:
addStartAndEnd = [[1, 2, 3, 4]] #the original list
temp_list = [-3, -2]
addStartAndEnd.append(temp_list)
test_list = addStartAndEnd[-1] #fetching the last item
test_list.append(-999) #appending a value only to test_list, nothing to do with addStartAndEnd
print("Final and test lists are:", test_list, addStartAndEnd)
Output is:
Final and test lists are: [-3, -2, -999] [[1, 2, 3, 4], [-3, -2, -999]]
-999 appended to the last item of the addStartAndEnd
list fetched inside the variable test_list
.