Reputation: 1858
I'm trying to understand the difference between references and objects. Please let me know if I'm not using the right terminology.
Consider the following code:
# SCENARIO 1
a = 1
b = a
a = 3
b # still 1, no surprises there
Also consider the following code:
# SCENARIO 2
class Node:
def __init__(self, link, value):
self.link = link
self.value = value
sll = Node(Node(None, 1), 2)
current = sll
current = current.link
current.value = 3
sll.link.value # updated to 3!
I've seen a lot of similarly phrased questions, but I still cannot understand what makes scenarios 1 and 2 different such that in scenario 2 we can update sll
by manipulating its reference, but we cannot do the same in scenario 1.
Upvotes: 2
Views: 61
Reputation: 1691
The two codes are essentially different. In scenario 1, yo do just assignments. It would be the same with Node
s (below I use simple list
instead):
# SCENARIO 1
a = 1
b = a
a = 3
b # still 1, no surprises there
# SCENARIO 1
a = [1]
b = a
a = [3]
b # still [1], no surprises there
Really does not matter what you use here.
# SCENARIO 2
sll = [1,2]
current = sll
current[0] = 3
sll[0] # updated to 3!
This is because sll
and current
are same objects. Different names, but the same object, the same place in memory.
You cannot do scenario 2 with int
and similar, because int
(and similar types) is immutable and you cannot do anything like a[0]=...
, a.value=...
, you simply cannot mutate it. You can mutate a list
(or a Node
in OP).
Upvotes: 3