-1

So, i just done my little experiment.

In the following Python code:

class TreeNode:
     def __init__(self, val=0, left=None, right=None):
         self.val = val
         self.left = left
         self.right = right

a = []
b = TreeNode(1)
a.append(b)
b = None

print(id(a[0]) # 140103806472096
print(id(b))   # 9520032

The first print gives different id than the second. What is happening to both a[0] and b after I assign None type to b? If the append() adds a reference to the list instead a copy as said here, why would these two ids differ and a[0] still stores the original TreeNode?

Lucius
  • 1
  • 2
  • Replace the `a.append` line with `c = b`. Are you surprised that `c` retains the old value even when you set `b = None`? Now apply that same reasoning to the `append` situation – Pranav Hosangadi Feb 12 '23 at 07:18
  • 1
    @PranavHosangadi I got wym. So under the hood append() still adds the reference, but it's just that assigning `b = None` assign a new PyObject to b and it's not interfering with the list or `c` in your case? – Lucius Feb 12 '23 at 07:34

1 Answers1

0

It's not about copy or reference to original object. You are observing normal python behavior in the matter of dynamic typing and garbage collection actually. The fact that you assign None to b means that b points to ("is a label for" if you will) None, which definitely has different memory address than your tree node. In your list however there's your tree node, since it hasn't been garbage collected. You would have to assign that node to something else to make such a comparison.

e.g.

a = []
b = c = TreeNode(1)
a.append(b)
b = None
print(id(c))
print(id(a[0]))

And then (after assigning None to b check the id of c. You will see it's the same (although you appended b and not c to the list)

There's a decent read about that: https://realpython.com/python-variables/

Gameplay
  • 1,142
  • 1
  • 4
  • 16
  • So u mean the old TreeNode assigned to `b` was garbage collected and a new None Type is assigned to `b`? – Lucius Feb 12 '23 at 07:35
  • As I said the TreeNode is not garbage collected at this time. The instance of node appended to the list and the one assigned to b and c is the same. The assignment of None to b doesn't affect it anyway it only causes the b to point to something else. – Gameplay Feb 12 '23 at 07:40