2

I was going through the Python DOC when I came upon lists and was confused by these :-

1.

>>> a = [1, 2, 3]
>>> b = a
>>> a.append(4)
>>> a
[1,2,3,4]
>>>b
[1,2,3,4]
>>> a = []
>>> print(a)
[]
>>> print(b)
[1, 2, 3, 4]

How can appending to a change both a and b but using a=[] only changes a and not b.

  1. As we know id(a) != id(a[:]) then why doing a[:]=[] changes a?

Thank you.

Mohit
  • 1,045
  • 4
  • 18
  • 45

1 Answers1

3

References are just variables that point to objects in memory. What you are doing with

b = a

is making b point to the same memory location to which a is currently pointing.

This means that through both variables b and a you can modify the same contents in memory, and this explains "why modifying b modifies also a".

Now, when you do

a = [] 

You are basically creataing a new empty list in memory and you are making a pointing to it...

Of course this is a general explanation, but I think it gives you the intuition.

nbro
  • 15,395
  • 32
  • 113
  • 196
  • Yeah, it may be so, can you explain the 2nd problem? – Mohit Jun 10 '15 at 17:27
  • Well, `id(a) != id(a[:])` returns `True` because the slice operator returns a new sublist, in this case the sublist happens to be a new object pointing to the same objects to which `a` is pointing. In the second case, `a[:]=[]`, my guess is that this is a _facility_ of Python of assigning a new object to a variable currently of type list, so it is the same thing as doing `a = []` (but I am not 100% sure). – nbro Jun 10 '15 at 17:34
  • @Mohit Check out the difference between `stack` and `heap`, and when an object is allocated on the stack and when on the heap, checkout the difference between references and objects, somewhere else, and you will understand better these concepts, which are really essential, and you basically need to know them by heart! – nbro Jun 10 '15 at 17:39
  • If the new sublist is pointing to original list wouldn't changing the main list also change the sublist.. for example:- `>>>for x in a[:]` `...a.pop()` it is seen that x iterates over all the original values as if popping has no effect in `a[:]` – Mohit Jun 10 '15 at 17:40
  • @Mohit In that case, `a[:]` is a new reference (of type list) pointing to the same objects to which `a` is pointing, and it is a local reference to the `for` loop, once the loop terminates, it will be garbage collected... Of course `x` will be pointing to the original objects in the list `a`, since that's what `a[:]` does.. – nbro Jun 10 '15 at 17:47