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]

Answer from trincot on Stack Overflow
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

🌐
Reddit
reddit.com › r/learnpython › is it possible to traverse a linked list in a for loop?
r/learnpython on Reddit: Is it possible to traverse a linked list in a for loop?
July 20, 2021 -

Consider the data structure defined like this (which is often used in Leetcode questions):

# Definition for singly-linked list.

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

So, we start by creating a temporary variable curr, letting it equal the head of the linked list. Then, to reach successive nodes, we repeatedly fetch curr.next and reassign that node instance to curr until we get None, which means we've reached the last node.

But can we make use of Python's __next__ magic method to make all this less cumbersome?

🌐
Reddit
reddit.com › r/learnpython › creating linked list using loops
r/learnpython on Reddit: Creating linked list using loops
July 12, 2022 -

I am having some difficulty understanding how linked lists can be created using an iterated loop.

class ListNode(object):
    def __init__(self, x):
        self.value = x
        self.next = None


def LinkedNodeTest(n):
    output = ListNode(0)
    temp = output
    for i in range(1, n+1):
        new = ListNode(i)
        temp.next = new
        temp = new
    return output

LinkedNodeTest(n) returns a linked list from 0 to n when it is called.

How is the variable 'output' being updated with the new nodes? I only see it being assigned ListNode(0) at the beginning of the function and it is not getting assigned in the for loop. It looks like assigning 'new' to 'temp' somehow updates 'output'; I don't really understand how that works.

Thanks for the help.

Top answer
1 of 5
2
temp = output When LinkedNodeTest begins, the first node is set to 0 and assigned to the output variable. That variable is then assigned to temp. So at this point, lets call the first node (ListNode(0)) NodeA. Before the loop begins, both output and temp are referencing NodeA. You can think of this as a = c; b = a; => b = c (=> denotes "therefore"). Now NodeA contains two attributes, value and next. It's important to know that in Python, everything is an object and "variables" are just names to memory addresses. When the loop begins, the first number assigned to i will be 1, and so new = ListNode(i) creates a new node with a value = 1, so we have: NodeA: value = 0, next = None NodeB: value = 1, next = None At this point, temp is still referring to what output was originally assigned to, NodeA. So temp.next is equivalent to NodeA.next. Then when new is assigned to it, you have: NodeA: value = 0, next = NodeB NodeB: value = 1, next = None Lastly, temp is reassigned to NodeB and this process continues where NodeC is created, incremented, assigned to the next attribute of NodeB, then assigned to temp, then NodeD is created, incremented, assigned to the next attribute of NodeC, so on and so forth: NodeA: value = 0, next = NodeB NodeB: value = 1, next = NodeC NodeC: value = 1, next = NodeD NodeD: value = 1, next = NodeE NodeE: value = 1, next = None ... So why is output never reassigned? Well it is the root node, and so this function returns to top most (i.e. root) element, so that you can access all the elements below it. If you assigned output to say NodeQ, you'd never be able to access NodeA through NodeP because a ListNode doesnt have an attribute that looks up, only down.
2 of 5
1
So the main thing about linked lists is that each node only knows where the next one is. When temp is output, you assign new to output.next. Then temp becomes new - which is the same object as output.next. So when you do temp.next = new the next time, that's the same as output.next.next = new. And so forth.
🌐
Stack Abuse
stackabuse.com › linked-lists-in-detail-with-python-examples-single-linked-lists
Linked Lists in Detail with Python Examples: Single Linked Lists
August 27, 2023 - Finally, if the list is not None and the element is not found at the first index, we create a new variable n and assign a start_node variable to it. Next, we traverse through the linked list using a while loop. It executes until n.ref becomes None. During each iteration, we check if the value ...
🌐
University of Toronto
cs.toronto.edu › ~david › course-notes › csc110-111 › 13-linked-lists › 02-traversing-linked-lists.html
13.2 Traversing Linked Lists
The following code is written to ... = 0 while i < len(my_list): ... do something with my_list[i] ... i = i + 1 ... Initialize the loop variable i to 0, referring to the starting index 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 - In the above example, we first created a Python class called “ListNode” with a val attribute to store the node’s value, and a next attribute to store a reference to the next node in the list. The next attribute was initially set to None, indicating that the node had no successor in the list. The while loop then traversed the linked list starting from the head node “node1” and printed each node’s value until the end of the list was reached, when “current_node” was None.
🌐
Real Python
realpython.com › linked-lists-python
Linked Lists in Python: An Introduction – Real Python
June 24, 2026 - First, you want to traverse the whole list until you reach the end (that is, until the for loop raises a StopIteration exception). Next, you want to set the current_node as the last node on the list.
Find elsewhere
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))
Top answer
1 of 2
6

If readability is a concern, why use single-character variable names? Replace them with something a bit more meaningful: v -> value, n -> next_, etc.


If you followed Python's data model your class could be used more easily and conventionally. For example, implementing size as a method seems a bit odd - if you called it __len__, then it would behave correctly with len and in a boolean context. Looking at the documentation for other, similar data structures can help with picking sensible names (I would expect an insert to take an index, for example, like the other sequences); in your case, maybe start with the deque's interface.

If you follow the conventional implementation, any of the following should work in a predictable way:

  • if thing in linked_list:
  • for thing in linked_list:
  • list(linked_list) (which would really simplify your __str__ implementation)
  • if linked_list:

You could also leverage Python's abstract base classes; if you inherit from Sequence and implement the required methods, for example, you get some additional behaviour for free.


In general you're following the style guide, but Node as a temporary variable name sticks out. It shadows the class you just instantiated and naming a variable in CamelCase is not the convention, it should be snake_case. In fact, it's entirely pointless; why not just self.node = Node(v, self.head)?

2 of 2
4

To make @jonrsharpe's suggestion more specific, this is one way to implement __iter__, without having to add another iterator class. It also gives you the __str__ method for free.

def __iter__(self):
    """
    Iterate over the linked list.
    """
    current = self.head
    while current is not None:
        yield current.value
        current = current.next

def __str__(self):
    """
    Prints the current list in the form of a Python list
    """
    return str(list(self))

Here is an example of its usage:

>>> l = LinkedList()
>>> l.insert(1)
>>> l.insert(2)
>>> for x in l:
...     print x
... 
2
1
>>> list(l)
[2, 1]
>>> print(l)
[2, 1]

Note that I used is not None instead of != None, read the answers here, if you want to know why.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-linked-list
Python Linked List - GeeksforGeeks
December 11, 2025 - Python Fundamentals · Introduction1 min read · Input & Output2 min read · Variables4 min read · Operators4 min read · Keywords2 min read · Data Types4 min read · Conditional Statements3 min read · Loops3 min read · Functions4 min read · Python Data Structures ·
🌐
Medium
medium.com › @deekshahareeshakulal › mastering-singly-linked-lists-a-complete-guide-with-python-8f0e4cef5491
Mastering Singly Linked Lists: A Complete Guide with Python | by Deeksha Hareesha Kulal | Medium
July 18, 2025 - def addTwoNums(l1,l2): summation = ListNode(0) current = summation carry = 0 while l1 or l2 or carry: val1 = l1.data if l1 else 0 val2 = l2.data if l2 else 0 total = val1+val2+carry carry = total//10 digit = total current.next = ListNode(digit) current = current.next if l1: l1 = l1.next if l2: l2 = l2.next return summation.next
Top answer
1 of 2
1

No, but you can use a list:

def make_nodes(n):
    nodes = []
    nodes.append(Node(0,None))    # head node
    for i in range(1, n):
        nodes.append(Node(i, None))
        nodes[i-1].next = nodes[i]    #somehow link them          
    return nodes

nodes = make_nodes()
head = nodes[0]
second = nodes[1]
last = nodes[-1]

You could also use a dictionary, and use the node number as the key. But a list seems more natural in this case.

But why would you want to do this? You might as well just use a Python list of Nodes. Creating the node list can be easily done with a list comprehension. Iterating over the list could then be done with a simple for loop:

nodes = [Node(i) for i in range(n)]

for node in nodes:
    print(node.payload)
2 of 2
0

You can use dictionaries and/or list to do what you are trying to achieve there.

But still if you are trying to test some data structure(s) for learning purpose you can create a class Node and work on it.

class Node(object):
    __data = None
    __ref_to_next = None

    def __init__(self, d):
        self.set_data(d)

    def set_data(self, d):
        self.__data = d

    def set_ref_to_next(self, r):
        self.__ref_to_next = r

    def append_a_node(self, new_node):
        cnode = self
        while cnode.__ref_to_next != None:
            cnode = cnode.__ref_to_next
        cnode.set_ref_to_next(new_node)

    def traverse(self):
        cnode = self
        while cnode.__ref_to_next != None:
            print cnode.__data
            cnode = cnode.__ref_to_next


def make_nodes(n):
    head_node = Node(0)
    for i in range(1,n):
        new_node = Node(i)
        head_node.append_a_node(new_node)

You can use the append function to populate the linked list simulation.

🌐
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.
🌐
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.
🌐
NeetCode
neetcode.io › courses › dsa-for-beginners › 5
NeetCode | Coding Interview Prep, Courses, Versus Mode
We start the traversal at the head of the list, which is ListNode1. We assign it to a variable cur, denoting the current node we are at. We execute the while loop until we reach the end of the list which is null.