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
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ python-linked-lists
Python Linked Lists
August 25, 2023 - Adding items to the list is done via add_list_item(). This method requires a node as an additional parameter. To make sure it is a proper node (an instance of class ListNode) the parameter is first verified using the built-in Python function isinstance(). If successful, the node will be added at the end of the list.
๐ŸŒ
Statistics Globe
statisticsglobe.com โ€บ home โ€บ python programming language for statistics & data science โ€บ what is a list node in python? (2 examples)
What is a List Node in Python? (2 Examples) | Linked List Structure
May 15, 2023 - class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # instantiate the nodes node1 = ListNode("The") node2 = ListNode("boy") node3 = ListNode("is") node4 = ListNode("tall") # link the nodes node1.next = node2 node2.next = node3 node3.next = node4 # traverse the linked list and print each node's value current_node = node1 while current_node is not None: print(current_node.val) current_node = current_node.next # The # boy # is # tall
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))
๐ŸŒ
CodeSignal
codesignal.com โ€บ learn โ€บ courses โ€บ getting-deep-into-complex-algorithms-for-interviews-with-python โ€บ lessons โ€บ linked-list-operations-in-python
Linked List Operations in Python
class ListNode: def __init__(self, value=0, next=None): self.value = value # Holds the value or data of the node self.next = next # Points to the next node in the linked list; default is None # Initialization of linked list head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
๐ŸŒ
CSCI 0112
cs0112.github.io โ€บ Lectures โ€บ lecture19.html
Linked Lists (Part 1) | CSCI 0112 - Fall 2024
October 21, 2024 - Letโ€™s make some classes that let us turn this into something we can write in Python. The picture above is a hint: we should probably have a kind of object to represent those links. class ListNode: def __init__(self, data): self.data = data self.next = None
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ [deleted by user]
[deleted by user] : r/learnpython
December 5, 2023 - # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next
๐ŸŒ
pytz
pythonhosted.org โ€บ llist
llist โ€” Linked list datatypes for Python โ€” llist 0.4 documentation
>>> from llist import sllist, sllistnode >>> empty_lst = sllist() # create an empty list >>> print(empty_lst) sllist() >>> print(len(empty_lst)) # display length of the list 0 >>> print(empty_lst.size) 0 >>> print(empty_lst.first) # display the first node (nonexistent) None >>> print(empty_lst.last) # display the last node (nonexistent) None >>> lst = sllist([1, 2, 3]) # create and initialize a list >>> print(lst) # display elements in the list sllist([1, 2, 3]) >>> print(len(lst)) # display length of the list 3 >>> print(lst.size) 3 >>> print(lst.nodeat(0)) # access nodes by index sllistnode(
Find elsewhere
๐ŸŒ
Real Python
realpython.com โ€บ linked-lists-python
Linked Lists in Python: An Introduction โ€“ Real Python
June 24, 2026 - Now, something you need to know about Python lists is that inserting or removing elements that are not at the end of the list requires some element shifting in the background, making the operation more complex in terms of time spent.
๐ŸŒ
Open Book Project
openbookproject.net โ€บ thinkcs โ€บ python โ€บ english2e โ€บ ch18.html
18. Linked lists โ€” How to Think Like a Computer Scientist: Learning with Python 2nd Edition documentation
The first line handles the base case by doing nothing. The next two lines split the list into head and tail. The last two lines print the list. The comma at the end of the last line keeps Python from printing a newline after each node.
๐ŸŒ
Readthedocs
jxmlease.readthedocs.io โ€บ en โ€บ stable โ€บ _modules โ€บ jxmlease โ€บ listnode.html
jxmlease.listnode โ€” jxmlease 1.0.1 documentation
""" # pylint: disable=global-statement # pylint: disable=invalid-name global XMLCDATANode global XMLDictNode global _resolve_references XMLCDATANode = _node_refs['XMLCDATANode'] XMLDictNode = _node_refs['XMLDictNode'] _resolve_references = lambda: None _resolve_references = _resolve_references_once def _get_dict_value_iter(arg, descr="node"): if isinstance(arg, XMLDictNode): try: # Python 2 return arg.itervalues() except AttributeError: # Python 3 return arg.values() elif isinstance(arg, XMLCDATANode): return [arg] else: raise TypeError("Unexpected type %s for %s" % (str(type(arg)), descr))
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ introduction-to-linked-lists-in-python
Linked Lists in Python โ€“ Explained with Examples
September 22, 2022 - By Fakorede Damilola Different programming languages offer different ways to store and access data. Some of the data structures you can use are collections such as arrays, lists, maps, sets, and so on. These all do an awesome job storing and accessi...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-library-for-linked-list
Python Library for Linked List - GeeksforGeeks
July 15, 2025 - To start with Python, it does not have a linked list library built into it like the classical programming languages. Python does have an inbuilt type list that works as a dynamic array but its operation shouldn't be confused with a typical function ...
๐ŸŒ
CodeRivers
coderivers.org โ€บ blog โ€บ listnode-python
Understanding and Using ListNode in Python - CodeRivers
July 21, 2026 - The val parameter represents the data value of the node, and the next parameter represents the reference to the next node. By default, val is set to 0 and next is set to None. The type hints (Optional[ListNode]) make the code self-documenting and enable static analysis tools like mypy to catch errors early.
๐ŸŒ
CodeQL
codeql.github.com โ€บ codeql-standard-libraries โ€บ python โ€บ semmle โ€บ python โ€บ Flow.qll โ€บ type.Flow$ListNode.html
ListNode - CodeQL - GitHub
CodeQL library for Python ยท codeql/python-all 7.1.2 (changelog, source) Index ยท Search ยท A control flow node corresponding to a list expression, such as [ 1, 3, 5, 7, 9 ] import python ยท SequenceNode ยท @py_flow_node ยท
๐ŸŒ
NBShare
nbshare.io โ€บ notebook โ€บ 212573943 โ€บ Why-do-we-use-Optional-ListNode-in-Python
Why do we use Optional ListNode in Python
In the above code, the find_node function takes a node of type Optional[ListNode] and a value of type int, and it returns a value of type Optional[ListNode]. This means that the node argument can be either a ListNode object or None, and the return value can be either a ListNode object or None. Using the Optional type in this way allows you to write functions that can handle None values more explicitly, making the code easier to read and understand. How to do SQL Select and Where Using Python Pandas
๐ŸŒ
CodeRivers
coderivers.org โ€บ blog โ€บ how-to-create-listnode-in-python
Creating ListNodes in Python: A Comprehensive Guide - CodeRivers
February 22, 2026 - A ListNode in Python typically consists of two main parts: - Value: This is the data that the node holds. It can be any Python data type, such as an integer, string, or even another object. - Next Pointer: This is a reference to the next node in the linked list.
Top answer
1 of 2
3

To get the output you have listed at the end of your question, you would need to create a linked list. For instance, if you define the following class:

class ListNode:
    def __init__(self, val, nxt=None):
        self.val = val
        self.next = nxt

    def __repr__(self):
        return f"ListNode{{val: {self.val}, next: {self.next}}}"

And if you then define list1 as follows:

list1 = ListNode(1, ListNode(2, ListNode(4, None)))

Then the "commands" will give the output that you listed.

List to Linked List

If you want to create the above linked list from the list [1,2,4], then use this function:

def createLinkedList(values):
    head = None
    for val in reversed(values):
        head = ListNode(val, head)
    return head

Now you can convert a plain list to a linked list as follows:

list1 = createLinkedList([1,2,4])

Linked List to list

If you want to do the opposite, and create a standard list from a linked list, then define this function:

def linkedListIterator(head):
    while head:
        yield head.val
        head = head.next

Now, if you have a linked list, you can pass it to the above function. For instance:

list1 = createLinkedList([1,2,4])
lst = list(linkedListIterator(list1))

lst will be [1,2,4]

2 of 2
0

As mentioned in the comments, it appears as though you are confusing a list with a singly linked list.

With the list provided you would just iterate with a for loop like this:

list1=[1,2,4]


for L in list1:
    print(L)

Which gives the output:

1
2
4

For linked lists, please refer to this: https://www.tutorialspoint.com/python_data_structure/python_linked_lists.htm

๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_dsa_linkedlists.asp
Linked Lists with Python
A Linked List is, as the word implies, a list where the nodes are linked together. Each node contains data and a pointer.
๐ŸŒ
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.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-linked-list
Python Linked List - GeeksforGeeks
December 11, 2025 - Your All-in-One Learning Portal. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.