The question doesn't require you to use regular lists. Since the lists are stored in "reverse order", that actually helps because you would add digits individually between both lists, then calculate/carry overflows moving left-to-right. For example, adding linkedlists [5, 1] + [5] would cause you to add one node to the resulting list [0, , then you iterate to the next position, carrying forward the 10s digit, then do 1 from your input plus 1 from the carry of the previous iteration, getting 2 , so the result is [0, 2]. If you carry a 1 into a 9, then you bring the carry digit forward again

Besides, if you're going to build a regular list, you might as well convert to an int, instead, do the math, then turn the int into the linked list...

But to convert a LinkedList into a regular list, without that LinkedList class being an iterable type itself, would look like this

ll = ListNode(...)

l = []
n = ll
while n is not None:
    l.append(n.val)
    n = n.next

Otherwise, if it were a proper Python iterable type, [n.val for n in ll]

Answer from OneCricketeer on Stack Overflow
Discussions

Help me out with ListNode
"ListNode" is not a thing in general Python or programming more widely. If the question references a ListNode class, it will certainly give the definition of that class. More on reddit.com
๐ŸŒ r/learnpython
12
0
July 10, 2025
linked list - Python Logic of ListNode in Leetcode - Stack Overflow
Question asking on Python's object ... Python's call-by-object style of passing function arguments ... Save this answer. ... Show activity on this post. For those reading this in the future: I wanted to debug linked list problems on a local environment so here is what I did. Modified the Leetcode code for ListNode by including ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
how do create a linked list in python - Stack Overflow
I am trying to solve a linked list coding challenge in python. And I have given only following class to create a linked list # Definition for singly-linked list. class ListNode(object): def More on stackoverflow.com
๐ŸŒ stackoverflow.com
loops - traverse listnode in python - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Save this question. Show activity on this post. Can someone help me with how can I traverse through below given listnode in python. I have written this command and am getting such outputs. ... list1 ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
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 ...
๐ŸŒ
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 - Therefore, in your preferred Python IDE, run the code below to create the sample linked list structure: class ListNode: def __init__(self,val=0,next=None): self.val = val self.next = next # instantiate the nodes node1 = ListNode() node2 = ListNode() node3 = ListNode() node4 = ListNode() # link the nodes node1.next = node2 node2.next = node3 node3.next = node4
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_dsa_linkedlists.asp
Linked Lists with Python
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... A Linked List is, as the word implies, a list where the nodes are linked together.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-linked-list
Python Linked List - GeeksforGeeks
December 11, 2025 - A linked list is a type of linear data structure individual items are not necessarily at contiguous locations.
๐ŸŒ
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!

Find elsewhere
๐ŸŒ
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
They provide an efficient way to ... tool in a programmer's toolkit. To work with linked lists, we first need to define a ListNode class, which represents a node in the linked list....
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))
๐ŸŒ
Real Python
realpython.com โ€บ linked-lists-python
Linked Lists in Python: An Introduction โ€“ Real Python
June 24, 2026 - Learn Python linked lists, deques, and circular & doubly linked structures with practical examples and efficient operations. Linked lists are an ordered collection of objects. So what makes them different from normal lists? Linked lists differ from lists in the way that they store elements in memory. While lists use a contiguous memory block to store references to their data, linked lists store references as part of their own elements.
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-linked-lists
Python Linked Lists: Tutorial With Examples | DataCamp
June 2, 2026 - Once you have a direct reference to the node at the insertion or deletion point, the operation itself is O(1). Still, finding that position still requires O(n) traversal, so the O(1) benefit only applies when you already hold a pointer to the relevant node (such as when working at the head of the list). Python lists are dynamic arrays, which means that they provide the flexibility to modify size.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python_data_structure โ€บ python_linked_lists.htm
Python - Linked Lists
Singly linked lists can be traversed in only forward direction starting form the first data element. We simply print the value of the next data element by assigning the pointer of the next node to the current data element.
๐ŸŒ
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.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ [deleted by user]
[deleted by user] : r/learnpython
December 5, 2023 - How do I convert this 'total' integer to a linked list? ... You don't, that is not a thing. You should be using the data structures you are given to solve this problem. ... ListNode(total), per the constructor, that's how the __init__ function is always called.
๐ŸŒ
Built In
builtin.com โ€บ data-science โ€บ python-linked-list
An Introduction to Python Linked List and How to Create One
In Python, linked lists can be built using custom classes for nodes and list operations ยท A linked list is an abstract data type that acts as a linear collection of data elements organized as a collection of nodes that contains information about what that node contains and then a link to another node.
๐ŸŒ
pytz
pythonhosted.org โ€บ llist
llist โ€” Linked list datatypes for Python โ€” llist 0.4 documentation
Negative indices are allowed (to count nodes from the right). Raises TypeError if index is not an integer. Raises IndexError if index is out of range. This method has O(n) complexity, but most recently accessed node is cached, so that accessing its neighbours is O(1). Note that inserting/deleting a node in the middle of the list will invalidate this cache.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ introduction-to-linked-lists-in-python
Linked Lists in Python โ€“ Explained with Examples
September 22, 2022 - Because of the chain-like system of linked lists, you can add and remove elements quickly. This also doesn't require reorganizing the data structure unlike arrays or lists. Linear data structures are often easier to implement using linked lists.
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

Top answer
1 of 4
7

Summary

I won't dwell on what has already been cited by users toolic and J_H, so I just have a few comments:

Type Hinting

I would suggest that you include type hinting, especially if your functions do not contain docstrings that describe the type of arguments being passed to functions (J_H has suggested this, so pardon if this is too repetitive).

Be More Tolerant of Errors in User Input

If the user does not enter a valid integer in function run_and_add, you essentially quit. You should instead put out the prompt again and give the user as many chances needed to enter valid input. The user can always terminate by entering Ctrl-C if they get stuck.

Strive for Encapsulation and Reusability

I can't stress too strongly that your code is crying out for you to create a LinkedList abstract data type that abstracts the notion of a linked list while encapsulating the actual implementation. To that end, I would use attribute names that begin with '_' where appropriate to suggest that they are "private" and not to be either updated nor depended on existing in the future (such as the next instance attribute of the ListNode class.

The following classes are just one possibility. Note:

  1. There is no print method implemented since printing the entire list is trivial given that the class implements the iterator protocol. Besides, what if you wanted to print to a file? Then a print method would require one or more additional arguments.
  2. The client never explicitly creates ListNode instances.
  3. The linked list keeps explicit track of the final (last) node in the list to provide efficient appending of a node or an entire linked list to the end.

I can envision your using this as a starting point and potentially adding other methods (for example, __eq__ methods to compare nodes and linked lists).

"""A module for creating and manipulating linked lists."""

from abc import ABC, abstractmethod
from typing import TypeVar, Any

LinkedListInstance = TypeVar('LinedListInstance', bound='LinkedList')

class NodeType(ABC):
    @property
    @abstractmethod
    def val(self):
        pass

    @val.setter
    @abstractmethod
    def val(self, val):
        pass

class LinkedList:

    class _ListNode(NodeType):
        """Initialize a new node with some value, val."""

        def __init__(self, val):
            self._val = val
            self._next = None

        @property
        def val(self):
            return self._val

        @val.setter
        def val(self, val):
            self._val = val

        def __repr__(self):
            return f'_ListNode({repr(self._val)})'

        def __str__(self):
            return str(self._val)

    def __init__(self):
        """Create a new, empty linked list."""

        self._head = None
        self._tail = None

    def append_node(self, val: Any) -> LinkedListInstance:
        """Append a new node to the list initialized with val."""

        new_node = LinkedList._ListNode(val)
        if self._head is None:
            self._head = new_node
        else:
            self._tail._next = new_node
        self._tail = new_node

        return self

    def insert_node(self, at_node: NodeType, val: Any) -> LinkedListInstance:
        """Create and insert a new node after the specified at_node node initialized
        with val."""

        if at_node is self._tail:  # special case
            return self.append_node(val)
        node_to_insert = LinkedList._ListNode(val)
        node_to_insert._next = at_node._next
        at_node._next = node_to_insert

        return self

    def append_list(self, linked_list: LinkedListInstance) -> LinkedListInstance:
        """Append a linked list to the current list."""

        if self._head is None:
            self._head = linked_list._head
        else:
            self._tail._next = self._head
        self._tail = linked_list._tail

        return self

    def __iter__(self) -> NodeType:
        """Iterate the list."""

        current = self._head
        while current is not None:
            yield current
            current = current._next

if __name__ == '__main__':
    def insert_node_at_position(linked_list: LinkedList, position: int) -> None:
        for counter, current_node in enumerate(linked_list, start=1):
            print(f"Node at position {counter}: {current_node}")
            if counter == position:
                while True:
                    try:
                        number = int(input("Please insert an Integer: "))
                    except ValueError:
                        print("Not an Integer")
                    else:
                        break
                linked_list.insert_node(current_node, number)
                print("Node added at position:", position)

        print("Updated linked list:")
        for node in linked_list:
            print(node)

    linked_list = LinkedList().append_node(1).append_node(2).append_node(3)
    insert_node_at_position(linked_list, 2)
2 of 4
6

names

class ListNode:

This is a perfectly fine identifier, as-is.

There's no adjacent code that uses other node types. Consider shortening to just Node.

design of Public API

OO

def print_linked_list(head):
...
def add_node(prev_node, node_to_add):
...

These are somewhat unexpected signatures, the sort of thing I might expect in Fortran code. ListNode turned out to be just a very brief @dataclass, with no OO aspect to it. Given a ListNode, we find no methods to call on it for list operations. This works, but makes it a little harder for developers and maintenance engineers to discover your API. For example if I hit a breakpoint() I cannot p dir(node) to find plausible things I might do with a node -- I instead have to scour the codebase for such operations.

Also, your signatures lack ListNode type annotations, so I can't just grep for that or use type-aware IDE features to narrow my search.

I propose some more natural implementations.

    def print_linked_list(self):
        head = self
        while head:
            print(head.val)
            head = head.next

    def add_node(self, node_to_add):
        assert node_to_add.next is None
        node_to_add.next = self.next
        self.next = node_to_add

Consider renaming these to simply .print() and .insert().

interactive input vs parameter

(I am paraphrasing, renaming the vague number to new_val.)

def run_and_add(head, position):
                ...
                new_val = int(input("Please insert an Integer: "))

Prefer to place calls of input() further up in the call stack, such as within def main():, and pass in such a value as a parameter:

def run_and_add(head, position, new_val):

main guard

On which topic, you don't have a main() function, and you really need one. Why? So you or some maintenance engineer can safely import linkedlist when exercising your functions in a test suite. Also, it's convenient to ensure that local variables like first (which are not part of your exported Public API) will disappear when they go out of scope. That way such identifiers won't pollute the module namespace.

def main():
    first = ListNode(1)
    first.next = ListNode(2)
    first.next.next = ListNode(3)
    run_and_add(first, 2)

if __name__ == '__main__':
    main()

single responsibility

run_and_add() is an awkward identifier, suggesting that instead of one we're doing two things. Also I find "run" less than clear.

Consider making caller responsible for passing in an already-created node, and then this could be a simple insert_at_position(head, position, new_node) function.