0

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
QUEEN
  • 383
  • 1
  • 5
  • 13
  • 1
    Did you mean: `test_list=addStartAndEnd[-1][:]`? This makes a copy of the last element. – quamrana Jun 18 '21 at 16:41
  • 2
    Mandatory link to [Ned Batchelder](https://nedbatchelder.com/text/names.html) – quamrana Jun 18 '21 at 16:41
  • thank you so much people @quamrana, but I wonder what's the difference between addStartAndEnd[-1][:] and addStartAndEnd[-1]? – QUEEN Jun 18 '21 at 16:51
  • 1
    Its what I said. `addStartAndEnd[-1]` is just a reference to the last element. `addStartAndEnd[-1][:]` is a reference to a copy of the last element. – quamrana Jun 18 '21 at 16:53

0 Answers0