-1

/* sample2 refers sample, yet when I update sample with {}, sample2 still have old keys and values */

sample={1:'one',2:'two',3:'three'}
sample2=sample   #reference
sample3=sample.copy()   #using copy method
sample
{1: 'one', 2: 'two', 3: 'three'}
sample2
{1: 'one', 2: 'two', 3: 'three'}
sample3
{1: 'one', 2: 'two', 3: 'three'}
sample.popitem()
(1, 'one')
sample
{2: 'two', 3: 'three'}
sample2
{2: 'two', 3: 'three'}
sample3
{1: 'one', 2: 'two', 3: 'three'}
sample={}
sample2
{2: 'two', 3: 'three'}

/*why sample2 still has those values, though being an reference for sample.

Varun
  • 7
  • 2
  • Note, this has nothing to do wtih `dict` objects, this is how *everything* works in Python. Read this: https://nedbatchelder.com/text/names.html – juanpa.arrivillaga Nov 30 '17 at 19:36

2 Answers2

1

sample2 is not a reference to sample! It is a reference to the same value (the dictionary data structure in the memory) that also goes by the name/reference sample.

There is no way that in Python a name can refer to another name. Names refer to values. Always.

sample={} re-assigns the name sample to another value. sample2 does not care about this.

timgeb
  • 76,762
  • 20
  • 123
  • 145
0

sample2 is not a reference to sample, but a reference to the value that sample had. When you do sample = {}, the old value still exists, and sample2 still references it, but sample1 now references {} instead.

internet_user
  • 3,149
  • 1
  • 20
  • 29