I declared two ListNode
objects as head = curr = ListNode(0)
. Now, to my surprise, both of them point at the same address:
>>> head
<__main__.ListNode object at 0x10bf271d0>
>>> curr
<__main__.ListNode object at 0x10bf271d0>
Why is that?
Why is it not like a = b = 4
?
Because, if I make changes to b
, a
doesn't get affected. However, if I make changes to curr
in the following manner, the head
can keep a track of it:
>>> curr.next = ListNode(1)
>>> curr = curr.next
>>> head
<__main__.ListNode object at 0x10bf271d0>
>>> curr
<__main__.ListNode object at 0x10bf27190>
>>> head.next
<__main__.ListNode object at 0x10bf27190>
I understand that head
and curr
are declared by refercing to pointers(address) and a
and b
are made by referencing to value. Is that right?
If yes, how can I control what gets declared with ref to value and what gets declared with ref to pointers(address)?
The ListNode
class used above is as follows:
>>> class ListNode(object):
... def __init__(self, x):
... self.val = x
... self.next = None
...
EDIT: Explanation of how this question is different from Mutable v/s Immutable Immutable vs Mutable types.
This question addresses the binding and referencing of the variables whereas the other question strictly talks about what Mutable and Immutable objects are in Python and their differences. While the latter does tell about the referencing of variables in order to explain Mutable v/s Immutable, it does not address the doubt that is asked in this question and hence, for the community, those confused observers would know the referencing concept due to this question.