Reputation: 107
I have linked list with the following structure.
class Node:
def __init__(self,val):
self.val = val
self.next = None
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
n1.next = n2
n2.next = n3
n3.next = n4
The last node's next is None , but when update it , it does reflect in the linked list.
a = n4.next
a = Node(5)
print(n4.next)
>> None
But when I directly update (without temp variable), it works
n4.next = Node(5)
print(n4.next)
>> <<Node Object>>
Why does this happen? I thought None is also an object in python and object assignments just copy references.
Upvotes: 2
Views: 689
Reputation: 3418
I think you're confusing the special Python None
singleton object with a normal Python class instance.
And you are confusing the classic programming language "variable" term (a container for value(s)) with references (variables that refer, or point to, containers of values)
In Python all variable names are references to objects.
So say you do something like
a = n1
a.val = 10
This would be reflected in n1
object (a Node class instance) because a
is a reference to n1
.
Trying to do something like
n4.next = None
a = n4.next
a = Node(3)
will make a
refer to None first, and then changes a
to refer to a different object, a new Node instance.
If a
refers to a Node instance, you can change the instance via a
n4.next = Node(2)
a = n4.next
a.val = 5 #this would alter n4.next
But if a
refers to the special object None, None will not act like a Node instance and hence cannot be changed
Upvotes: 3