0

Can someone please explain how this is possible??

>>> a = [1,2,3,4,5,5,5,5,4,3,2,2]
>>> a
[1, 2, 3, 4, 5, 5, 5, 5, 4, 3, 2, 2]
>>> b = a
>>> b.remove(1)
>>> b
[2, 3, 4, 5, 5, 5, 5, 4, 3, 2, 2]
>>> a
[2, 3, 4, 5, 5, 5, 5, 4, 3, 2, 2]

How is the remove method able to access a when I called it on b? I can work around this by importing copy and copying the list that way but If someone can explain how the above is possible that would be amazing!

Blockquote

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
LaPepita
  • 29
  • 2
  • Because b is a copy of a and share the same memory address – heinst May 14 '15 at 13:43
  • 3
    You didn't create copies, you created additional references to the list. – Martijn Pieters May 14 '15 at 13:43
  • 2
    `b = a[:]` will do the job – ZdaR May 14 '15 at 13:44
  • Read http://nedbatchelder.com/text/names.html – Alik May 14 '15 at 13:44
  • 3
    @MartijnPieters Hi again! I dont think this was a duplicate of that question because he was asking if someone could explain why this is the way it is. Not how to copy a list – heinst May 14 '15 at 13:44
  • Thank you for the prompt response, I now understand. Still new to Python – LaPepita May 14 '15 at 13:45
  • See also http://stackoverflow.com/q/2438938/3001761 – jonrsharpe May 14 '15 at 13:45
  • @LaPepita If you do `print 'Memory address of a: ', id(a) print 'Memory address of b: ', id(b)` you will see that the lists are referencing the same memory address so when you remove it from b, you remove it from a since they are coming from the same memory location – heinst May 14 '15 at 13:48
  • @heinst: but the underlying issue is that they thought they had created a copy. They had not. This crops up time and again. – Martijn Pieters May 14 '15 at 13:52
  • @heinst: if you read the other question carefully, you'll see that it covers the exact same ground. – Martijn Pieters May 14 '15 at 13:52
  • @MartijnPieters I think hes honestly asking why this is, because he states how he can work around it, but ok! – heinst May 14 '15 at 13:53
  • @heinst: there is even a [specific answer](https://stackoverflow.com/a/27091494) on the other post explaining why not copying creates another reference to the same object. – Martijn Pieters May 14 '15 at 13:54

0 Answers0