-3

When value is popped off a dict:

  1. Example of assignment: x = dict1.pop()

Here the popped value gets assigned to x. Is this pointer assignment or shallow or deep copy?

  1. Example of no assignment: dict1.pop()

What happens to the popped value? Where does it go when no assignment is made?

petezurich
  • 9,280
  • 9
  • 43
  • 57
variable
  • 8,262
  • 9
  • 95
  • 215

1 Answers1

2

The pop method on a dictionary returns a reference to the actual value, not a copy of it: so is confirms that it's the same as the original value, by identity.

>>> obj = object()
>>> d = {'foo': obj}
>>> d.pop('foo') is obj
True

If you don't assign the result or use it anywhere, then it's just silently discarded. You can observe using sys.getrefcount that there is one fewer reference to the value after popping it, since there is no longer a reference to it from the dictionary, and popping it without using the result somehow means no new reference is created:

import sys

obj = object()
d = {'foo': obj}

print('Before popping:', sys.getrefcount(obj))

d.pop('foo')
print('After popping:', sys.getrefcount(obj))

Output (the refcount is inflated by 1 due to getrefcount's parameter also being counted):

Before popping: 3
After popping: 2
kaya3
  • 47,440
  • 4
  • 68
  • 97