0

I have assigned values for variables like this. It's worked nice.

In [16]: var1 = var2 = 5
In [17]: var1 = 2
In [18]: var2
Out[18]: 5
In [19]: var1
Out[19]: 2

Same operations done with list.

In [20]: list1 = list2 = []
In [21]: list1.append(5)
In [22]: list1
Out[22]: [5]
In [23]: list2
Out[23]: [5]

Same method i initialized two lists. After insert value in list1 but it's effect the value of list2. How it's happening. I wonder why it's happening like this. Anyone please explain.

Thanks

Rahul K P
  • 15,740
  • 4
  • 35
  • 52
  • Note that these are *not* the same operations; in the first one you rebind `var1`, but in the second one you *mutate* `list1`. – Daniel Roseman May 23 '16 at 14:28

1 Answers1

5

After you say list1 = list2 = [], list1 and list2 are the same list object. So when you add new elements to that object, they are there whether you access it by the name list1 or by the name list2.

The answers to this earlier SO question may be enlightening. (Perhaps this question should be marked a duplicate of that one?)

Community
  • 1
  • 1
Gareth McCaughan
  • 19,888
  • 1
  • 41
  • 62
  • As per programming it's should be different objects right ? Is it a defect of 'Python` language or my way of coding ? – Rahul K P May 23 '16 at 14:19
  • Nope, they are two names for the exact same object. – Gareth McCaughan May 23 '16 at 14:19
  • You can explicitly make a copy if you want to: e.g., `list2 = list1[:]` will make a new list with the same elements, and then modifying one will not change the other. – Gareth McCaughan May 23 '16 at 14:20
  • It's not about problem solving. I can initialize independently. But My doubt is s it a defect of 'Python` language or my way of coding ? – Rahul K P May 23 '16 at 14:23
  • 2
    It's a feature of Python. *Assignment by Reference*. – totoro May 23 '16 at 14:24
  • 4
    Python behaves this way by design (so it's not a defect in the sense of a *bug*) and it's a pretty sensible (and common) way for a language to behave (so it's not a defect in the sense of a *design flaw*). If you write Python code on the assumption that saying `a=b` takes a copy of whatever's in `b` rather than just making `a` another name for it, then that's a defect in your way of coding because in fact assignment doesn't do that in Python. – Gareth McCaughan May 23 '16 at 14:24
  • OK. Thank you for your valuable comments. – Rahul K P May 23 '16 at 14:26
  • (But *wanting* it to work a different way isn't necessarily a defect in your way of coding. There are languages in which assignment generally means copying -- for instance, C++ and MATLAB -- and those are clearly also languages in which one can get real work done. Personally, I find the Python way clearer for most purposes.) – Gareth McCaughan May 23 '16 at 14:27