2

Today, due to a weird behavior in an application's functionality, I discovered this strange behavior of Python assignment operator which I was completely oblivious to.

As per my understanding, '=' operator is meant to assign values to variables.

So I tried this:

>>> x = 5    --> assigned integer 5 to x
>>> y = x    --> assigned value of 'x' (5) to y 
>>> y = 6    --> assigned integer 6 to y
>>> x        
5            --> x remains 5 (unchanged)
>>> y
6            --> y changes to 6 (as expected)

But then I tried the same thing with lists:

>>> x = []    --> assigned empty list to x
>>> y = x     --> assigned value of 'x' (empty list) to y
>>>
>>> y.append({'id': 2}) --> updated value of y
>>>
>>> y
[{'id': 2}]    --> y changes to new value (as expected)
>>>
>>> x
[{'id': 2}]    --> x changes to new value (un-expected. How ???????)

Can someone explain why this difference in behavior?

Utkarsh Sinha
  • 941
  • 2
  • 11
  • 30
  • 2
    Mandatory link to Ned Batchelder's article about [names](https://nedbatchelder.com/text/names.html) – quamrana Apr 14 '20 at 15:32
  • You will also find that the behaviour observed in the first snippet is as you expect in this snippet: `x=[5]; y=x; y=[6]` – quamrana Apr 14 '20 at 15:35
  • Also your assertion in the second snippet of:`updated value of y` is not true. The `append()` method is updating the `list` that `y` happens to refer to. – quamrana Apr 14 '20 at 15:38
  • @quamrana thanks for sharing the link to Ned's article. It's what I was looking for. – Utkarsh Sinha Apr 14 '20 at 16:48

0 Answers0