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:

  1. result and result_tail are two variables that happen to point at the same value
  2. Mutation / Changing of the underlying value (result_tail.next = ListNode(1)) will affect the value shown by result
  3. However, assigning / pointing the variable result_tail to another value will NOT affect the value of result
  4. 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
Answer from Joseph on Stack Overflow
🌐
GitHub
github.com › menghany › LeetCode-Python › blob › master › ListNode.py
LeetCode-Python/ListNode.py at master · menghany/LeetCode-Python
Solutions coded by Python to LeetCode. Contribute to menghany/LeetCode-Python development by creating an account on GitHub.
Author: menghany
Top answer
1 of 4
27

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:

  1. result and result_tail are two variables that happen to point at the same value
  2. Mutation / Changing of the underlying value (result_tail.next = ListNode(1)) will affect the value shown by result
  3. However, assigning / pointing the variable result_tail to another value will NOT affect the value of result
  4. 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
2 of 4
16

For those reading this in the future: I wanted to debug linked list problems on a local environment so here is what I did.

  1. Modified the Leetcode code for ListNode by including the dunder "repr" method. This is for when you want to print a ListNode to see what its value and next node(s).
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

    def __repr__(self):
        return "ListNode(val=" + str(self.val) + ", next={" + str(self.next) + "})"
  1. Next, I made a recursive function that makes a nested ListNode when you pass in a list. This is so you can test your methods by passing in lists (instead of having to manually make a confusing looking ListNode yourself.
def list_to_LL(arr):
    if len(arr) < 1:
        return None

    if len(arr) == 1:
        return ListNode(arr[0])
    return ListNode(arr[0], next=list_to_LL(arr[1:]))
  1. Here is an example that tests my answer for the "reverseList" problem:
def reverseList(head: ListNode) -> ListNode:
    prev = None
    while head:
        next_node = head.next
        head.next = prev
        prev = head
        head = next_node

    return prev


# test cases
t1 = list_to_LL([1, 2, 3, 4, 5])  #ListNode(val=1, next={ListNode(val=2, next={ListNode(val=3, next={ListNode(val=4, next={ListNode(val=5, next={None})})})})})
t2 = list_to_LL([1, 2])  #ListNode(val=1, next={ListNode(val=2, next={None})})
t3 = list_to_LL([])

# answers
print(reverseList(t1))
print(reverseList(t2))
print(reverseList(t3))
Discussions

python - How to convert ListNode from LeetCode to regular list? - Stack Overflow
Trying to solve LeetCode "Add Two Numbers". You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes More on stackoverflow.com
🌐 stackoverflow.com
How does ListNode work in LeetCode?
Also, while I was working on this I also wondered, is there a way to check the class files for the standard library or any other library? I want to check the code for the LinkedList and other classes in the future for clarity. Yes, the code for the Java standard library is all open-source, along with the rest of the JDK and JVM. Of course, you shouldn't just blindly copy the way the JDK does things without understanding them. Here's the code for the LinkedList class: https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/LinkedList.java Notice that it has a nested inner class called Node, which has item and next fields, just like the ListNode class in the LeetCode problem. (It also has a prev field, making it a doubly-linked list.) But LinkedList doesn't expose its nodes to outside users. It only allows you to interact with them indirectly, through methods on the LinkedList class itself, to provide encapsulation . More on reddit.com
🌐 r/learnprogramming
8
3
July 3, 2024
An easy leetcode question
Leetcode question 237, delete a node in a linked list, an easy question It is said to be an easy question. What bothers me is that I do not know how to implement it on my own computer. I need a full example. Moreover, Leetcode provides a list, not a linked list. More on discuss.python.org
🌐 discuss.python.org
1
0
February 23, 2022
How to understand the data structure of Python Linked List in Leetcode - Stack Overflow
I am really confused by the Python linked list data structure used in Leetcode. I am not sure if the problem is caused by the specific ListNode structure created by Leetcode, or I have some More on stackoverflow.com
🌐 stackoverflow.com
Author: bhardwajRahul
🌐
LeetCode
leetcode.com › problems › Add-Two-Numbers › discuss › 174970 › Help-with-ListNode-(Python)
Loading...
September 27, 2018 - Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
🌐
GitHub
github.com › mcclee › Leetcode-python-Listnode
GitHub - mcclee/Leetcode-python-Listnode: A python class to convert list to Listnode · GitHub
A python class to convert list to Listnode Usage: from ListToListnode import FuckListnode list1 = [1, 2, 3, 4] f = FuckListnode() listnode = f.returnNode(list1)
Author: mcclee
Find elsewhere
🌐
PyPI
pypi.org › project › leetcode-py-sdk › 1.0.13
leetcode-py-sdk · PyPI
A Python package to generate professional LeetCode practice environments: a problem README, a typed solution stub, a parametrized pytest suite with 10+ cases, helpers, and a playground notebook, all from JSON templates.
🌐
Reddit
reddit.com › r/learnprogramming › how does listnode work in leetcode?
r/learnprogramming on Reddit: How does ListNode work in LeetCode?
July 3, 2024 -

I've decided to tackle my first medium problem on Leetcode, Add Two Numbers (Java), but I've hit a wall. I started by reading the task and looking at the description, but after doing some research I just can't grasp how the ListNode class works. Here is its code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

I understand that it is supposed to work similar to the java.util.LinkedList class, but I don't get how. It holds two methods besides the default constructor and they only seem to set the values of int val and ListNode next. I am lost at how this chunk of code creates a singly-linked list, as I learned how to use one, but not how it works under the hood. I thought maybe it had something to do with the keyword "this", but after researching even more I learned that it is used to refer to the class property and not the parameter.

Also, while I was working on this I also wondered, is there a way to check the class files for the standard library or any other library? I want to check the code for the LinkedList and other classes in the future for clarity.

🌐
LeetCode
leetcode.com › discuss › general-discussion › 388183 › improving-listnode-definition-for-python-problems
Improving ListNode definition for python problems - Discuss - LeetCode
This definition initialise a listnode without a next value, it is very clunky to use in recursion class ListNode: def init(self, x): self.val = x
🌐
GitHub
github.com › lyfu19 › Leetcode-Py › blob › main › ListNode.py
Leetcode-Py/ListNode.py at main · lyfu19/Leetcode-Py
Practicing on Leetcode using Python ~. Contribute to lyfu19/Leetcode-Py development by creating an account on GitHub.
Author: lyfu19
🌐
Python.org
discuss.python.org › python help
An easy leetcode question - Python Help - Discussions on Python.org
February 23, 2022 - Leetcode question 237, delete a node in a linked list, an easy question It is said to be an easy question. What bothers me is that I do not know how to implement it on my own computer. I need a full example. Moreover, Leetcode provides a list, not a linked list.
🌐
PyPI
pypi.org › project › leetnode
Client Challenge
June 3, 2020 - JavaScript is disabled in your browser · Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
LeetCode
leetcode.com › problems › mini-parser › solutions › 1578496 › Python-or-8-lines-of-code-built-in-json-parser.
Mini Parser - LeetCode
Can you solve this real interview question? Mini Parser - Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return the deserialized NestedInteger.
🌐
Reddit
reddit.com › r/learnpython › help me out with listnode
r/learnpython on Reddit: Help me out with ListNode
July 10, 2025 -

Hello all, I completed my 12th this may( high school graduate ) going to attend Engineering classes from next month. So I decided to start LeetCode question. Till now I have completed about 13 questions which includes 9 easy ones, 3 medium ones and 1 hard question( in python language ) with whatever was thought to me in my school, but recently I see many questions in from ***ListNode***, but searching in youtube doesn't shows anything about ListNode but only about Linked list. So kindly suggest me or provide the resources to learn more about it.

Thank you!

🌐
LeetCode
leetcode.com › problems › reverse-linked-list › solutions › 172785 › Python-simple-code-by-using-ListNode-class-definition-(OOP-style).
Python simple code by using ListNode class definition ...
September 21, 2018 - Can you solve this real interview question? Reverse Linked List - Given the head of a singly linked list, reverse the list, and return the reversed list. Example 1: [https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg] Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Example 2: [https://assets.leetcode.com/uploads/2021/02/19/rev1ex2.jpg] Input: head = [1,2] Output: [2,1] Example 3: Input: head = [] Output: [] Constraints: * The number of nodes in the list is the range [0, 5000]. * -5000
🌐
Reddit
reddit.com › r/leetcode › learning python in-depth as new interview language -- what is this "optional [listnode]"?
r/leetcode on Reddit: Learning python in-depth as new interview language -- what is this "Optional [ListNode]"?
October 4, 2022 - So Optional[ListNode] means that either the return value is of type ListNode, or potentially None which in this case would be if your linked list is empty (hence head is also potentially None or a ListNode type).
🌐
LeetCode
leetcode.com › problems › add-two-numbers › solutions › 1264577 › python-solution-by-create-a-new-listnode
Python Solution (by Create a New ListNode) - Add Two ...
June 11, 2021 - Can you solve this real interview question? Add Two Numbers - You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit.