0
>>> a = 100
>>> b =a
>>> b = b+ 10
>>> b
110
>>> a
100

>>> a = [1,2,3]
>>> b = a
>>> b.insert(0,0)
>>> b
[0, 1, 2, 3]
>>> a
[0, 1, 2, 3]

Why the behaviour is different in case when a is int and when a is list ? What should I do if I want to preserve the value of list a??

tryPy
  • 71
  • 1
  • 9
  • 1
    When you call `b.insert()` you are altering an existing mutable object, but `b = b + 10` *rebinds* `b` to reference a new value. Up to that point `a` and `b` were referencing the same object. You could do the same for lists: `a = [1, 2, 3]; b = a; b = [0] + b` would rebind `b` to a new list object. – Martijn Pieters Nov 18 '14 at 18:09
  • @MartijnPieters Thanks dude – tryPy Nov 18 '14 at 18:20

0 Answers0