0
a = [1]
b = a
a.append(2)
print(b)
-------output--------
[1,2]

Can anyone explain me the reason why b value is updated when we update the value of a ???

  • `b = a` means you create a reference of a list, not a new list. If you want to create a copy you need to tell python, e.g. `b = a.copy()` otherwise b is just a reference, or lets say a synonym for a. – Andreas May 11 '21 at 12:58
  • 1
    `b = a` does not make a *copy* of the list; it just makes a second name for the same list. Read https://nedbatchelder.com/text/names.html. – chepner May 11 '21 at 12:58
  • You might want to check out the difference between mutable and immutable data types in Python too! =) – Tim Jim May 11 '21 at 12:58
  • 2
    @TimJim The OP expected `a` to be changed, just not `b`. – chepner May 11 '21 at 12:59
  • "Assignment statements in Python do not copy objects, they create bindings between a target and an object. " (cf. [docs.python.org](https://docs.python.org/3/library/copy.html)) – XtianP May 11 '21 at 12:59
  • @chepner ah yes, you're right - I just skimmed through on my way past! I had mutable python containers on my mind at the time – Tim Jim May 11 '21 at 13:00

0 Answers0