While solving the Merge k Sorted Lists (LeetCode 23) I came out with a working code that can be summarised like this :
for key in values.keys():
current = ListNode(key, prev)
prev = current
My question is : When passing an object to a class Initialiser (ListNode is the class and prev is the argument in question), Is it passed as reference ? So when i later change prev outside that class does it also changes in the class i just created ? Because I thought yes and I was expecting to encounter a cycle running the code above, but it actually works fine. Which means that once i pass prev to that class and then i modify prev outside, the changes do not reflect in current.
If any of you struggles with these type of concept and edge cases in the past could give me some reference or example that might help me consolidate my knowledge ?
For example passing prev to a function and then changing it in the function would it changes its value outside. Or changing it inside the class would it change it also outside ?
UPDATE: Basically my doubt is better visualised in this code :
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
first = ListNode(4, None) # 4, None
second = ListNode(3, first) # 3, 4
first = ListNode(3, None) # 3, None
print(second.next.val) # => 4
I was expecting that by printing second.next.val i would have got 3 while i still get 4. This sound very strange to me but actually looking at this other bit of code is quite intuitive :
first = 1
second = 2+first
first = 4
print(second) # => 3