0

Learning python..please go easy! :)

Lets say i make a dict as below :

In [10]: a = {"a":"a", "b":"b"}

In [11]: a
Out[11]: {'a': 'a', 'b': 'b'}

In [12]: b = a

In [13]: b
Out[13]: {'a': 'a', 'b': 'b'}

In [14]: c = b

Now, a, b and c all point to same dict,so if i do :

In [15]: c.update({"c":"c"})

Then, understandably, all references get updated :

In [16]: c
Out[16]: {'a': 'a', 'b': 'b', 'c': 'c'}

In [17]: b
Out[17]: {'a': 'a', 'b': 'b', 'c': 'c'}

In [18]: a
Out[18]: {'a': 'a', 'b': 'b', 'c': 'c'}

But same thing won't work in below case :

In [1]: a = 3

In [2]: b = a

In [3]: c = []

In [4]: c.append(b)

In [5]: a
Out[5]: 3

In [6]: b
Out[6]: 3

In [7]: c
Out[7]: [3]

In [8]: a = 5

In [9]: b
Out[9]: 3    #  this should have printed 5 and not 3 as per my understanding

I am confused as to how python places the references internally!! Does it not apply for int, str types or is there some special case?

NoobEditor
  • 15,563
  • 19
  • 81
  • 112
  • Briefly: `a = 5` makes `a` refer to a new object, which won't necessarily have the same identity as the object it used to point to. – TigerhawkT3 Jan 23 '16 at 04:20
  • @TigerhawkT3 right but isn't `b` pointing to `a`? so if `a` starts pointing to some new value, `b` should also refer to that? Or is it that its more based on memory address, `a = 5` create a new references whereas `b=a` still points to old address of `a`? – NoobEditor Jan 23 '16 at 04:26
  • 1
    `b` and `a` point to the same object initially. When you do `a = 5` you make `a` point to a different object, the integer `5`. – kindall Jan 23 '16 at 04:30
  • 1
    You write "a" on a sticky note and attach it to a 3-year-old kid. You write "b" on a sticky note and attach it to that same 3-year-old. You take the "a" sticky note and put it on a 5-year-old kid. The "b" sticky note is still where you left it. Note: don't try this at home. – TigerhawkT3 Jan 23 '16 at 04:45
  • @TigerhawkT3 : kids always help me understand things in better manner....wont try at hope, don't wry!! :D – NoobEditor Jan 23 '16 at 04:52

0 Answers0