The short answer to this is that, Python is a pass-by-object-reference language, not pass-by-reference as implied in the question. It means that:
result
andresult_tail
are two variables that happen to point at the same value- Mutation / Changing of the underlying value (
result_tail.next = ListNode(1)
) will affect the value shown byresult
- However, assigning / pointing the variable
result_tail
to another value will NOT affect the value ofresult
result_tail = result_tail.next
is assigning the next node of the node that is currently assigned by the variable
The following is an visualization of the values that are assigned to the variables (r
= result
, rt
= result_tail
):
result = ListNode(0) #r #0 -> None result_tail = result #r #0 -> None #rt result_tail.next = ListNode(1) #r #0 -> 1 -> None #rt result_tail = result_tail.next #r #0 -> 1 -> None # rt result_tail.next = ListNode(2) #r #0 -> 1 -> 2 -> None # rt result_tail = result_tail.next #r #0 -> 1 -> 2 -> None # rt
References for additional reading:
- An article explaining the Python pass-by-object reference style in detail https://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/
- An answer explaining Python’s pass-by-object reference style https://stackoverflow.com/a/33066581/12295149
- Question asking on Python’s object reference style Understanding Python’s call-by-object style of passing function arguments