You should do val = val.next instead of val.next = val.next.next. The way you're doing it, the list will be truncated to a single element when you call count_length. Because you do count_length at the top of kth_to_last, by the time you get around to walking your list (where your 'hi' is), the list has already been reduced to a single node.

Remember, a linked list is a structure where each node's next property is a pointer to the next node. Your code is modifying the value of next, which is changing the structure of your linked list.

When you process a linked list (in count_length, or in kth_to_last), what you want to do is point yourself at each node in turn. You're not trying to modify the nodes themselves, so you won't assign to their value or next attributes. The way to do this is to change what your pointer (val) is pointing at, and the thing that you want it to point at next is the next node along. Therefore:

val = ll.head
while val is not None:
    # do something with val here
    val = val.next
Answer from wildwilhelm on Stack Overflow
🌐
Reddit
reddit.com › r/learnprogramming › what does 'next' point to exactly in a linked list? does it point to the remaining list node or the next node?
r/learnprogramming on Reddit: What does 'next' point to exactly in a linked list? Does it point to the remaining list node or the next node?
April 12, 2023 -

I was trying the Merge Two Sorted Lists question from Leetcode and had a pretty fundamental doubt. This is the solution of the code in Python:

def mergeTwoLists(self, list1, list2):
        dummy = ListNode()
        tail = dummy
        while list1 and list2:
            if list1.val < list2.val:
                tail.next = list1
                list1 = list1.next
            else:
                tail.next = list2
                list2 = list2.next
            tail = tail.next
        if list1:
            tail.next = list1
        elif list2:
            tail.next = list2
        return dummy.next

Here, we are returning dummy.next as a representation of the final merged linked list but I thought that the next attribute pointed to only the next node? My understanding was that we would need to return tail since that represents the list node as a whole?

Discussions

python - Setting a next value for a linkedlist function - Stack Overflow
How does returning dummyHead.next works? This value wasn't modified, it's just an empty list in the beginning · I tried to debug but I still haven't gotten much out of it. I'm trying to learn LinkedList from this example and would appreciate any help. Huge thanks ahead! ... Basic thing to remember about Python ... More on stackoverflow.com
🌐 stackoverflow.com
iterator - implementing __next__() in python linked list - Stack Overflow
I would like to retrieve a particular node in a linked list by iterating a specified number of times; for example, to retrieve the 4th node. By implementing __iter__(), I can iterate with a for loo... More on stackoverflow.com
🌐 stackoverflow.com
April 18, 2021
linked list iterator python - Stack Overflow
I want to write a function called ... items in a linked list by making use of the Iterator. However, you are not permitted to use the standard "for ... in" loop syntax - instead you must create the Iterator object explicitly, and print each item by calling the next() ... More on stackoverflow.com
🌐 stackoverflow.com
Can somebody explain linked lists in python I'm struggling so bad :(
Insert creates a new Node, named newNode. If there's already a head Node in the LinkedList, current is set to the head and then it's advanced to the end of the list, then newNode is inserted there. If there's no head node, the newNode is made the head. More on reddit.com
🌐 r/learnprogramming
6
3
October 18, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-linked-list
Python Linked List - GeeksforGeeks
December 11, 2025 - Example: Below is a simple example to create a singly linked list with three nodes containing integer data. ... class Node: def __init__(self, data): self.data = data self.next = None # Create nodes node1 = Node(15) node2 = Node(3) node3 = Node(17) node4 = Node(90) # Link nodes node1.next = node2 node2.next = node3 node3.next = node4 head = node1 # Head points to the first node # Traverse and print the linked list current = head while current: print(current.data, end=" -> ") current = current.next print("None")
Top answer
1 of 1
1

why set curr.next to newNode and then completely overwrite it with curr = newNode?

These are two different type of assignment. The first -- assigning to curr.next -- mutates whatever object that curr is referencing. The second -- curr = newNode -- merely changes what curr references to. It doesn't mutate the data structure. It may help to visualise what happens. Let's say curr references a ListNode instance with value 1:

curr
  │
┌─┴──────────┐
│ val: 1     │
│ next: None │
└────────────┘

And newNode was just created with a value 2:

curr              newNode
  │                 │
┌─┴──────────┐    ┌─┴──────────┐
│ val: 1     │    │ val: 2     │
│ next: None │    │ next: None │
└────────────┘    └────────────┘

Then the first assignment -- curr.next = newNode will accomplish this:

curr              newNode
  │                 │
┌─┴──────────┐    ┌─┴──────────┐
│ val: 1     │    │ val: 2     │
│ next: ──────────┤ next: None │
└────────────┘    └────────────┘

And the second assignment, leads to this state:

                  curr newNode
                    │    │
┌────────────┐    ┌─┴────┴─────┐
│ val: 1     │    │ val: 2     │
│ next: ──────────┤ next: None │
└────────────┘    └────────────┘

The same would have happened, if the second assignment would have been curr = curr.next, since at that point curr.next and newNode reference the same object. This should also explain the rationale for your second point concerning l1 = l1.next. This merely traverses one step through a linked list with a variable. It doesn't affect that linked list itself.

How does returning dummyHead.next works? This value wasn't modified, it's just an empty list in the beginning.

The list was modified. But it happened via a different variable... curr. Note how initially curr references the same object as dummyHead, and then in the loop, the assignment to curr.next is setting the next attribute that dummyHead references, so that now dummyHead.next references a list with one element. And curr will move on to reference that element, and again set its next attribute, making that linked list having 2 nodes, ...etc

🌐
Medium
medium.com › @mondalsabbha › introduction-to-linked-lists-in-python-a-comprehensive-guide-093416668f70
Introduction to Linked Lists in Python: A Comprehensive Guide 🔗 | by Sabbha Mondal | Medium
August 14, 2024 - The first node of a linked list is called the head. The last node has a next reference that points to None, indicating the end of the list.
🌐
W3Schools
w3schools.com › python › python_dsa_linkedlists.asp
Linked Lists with Python
If you want to delete a node in a linked list, it is important to connect the nodes on each side of the node before deleting it, so that the linked list is not broken. So before deleting the node, we need to get the next pointer from the previous node, and connect the previous node to the new next node before deleting the node in between.
Find elsewhere
🌐
Mga
comp.mga.edu › learning › python › module › 18
18. Linked Lists | Learning Python | School of Computing | Middle Georgia State University
When inserting a new node in the middle of the list, declare a variable, current, and point it to the head node. Iterate through the nodes using a loop while moving to the previous node until the desired index is reached. And declare a variable, temp and point it to the next node of the current node. Link the new node, “Chicago” to the current.next node.
🌐
Stack Abuse
stackabuse.com › python-linked-lists
Python Linked Lists
August 25, 2023 - The list_length() method counts the number of nodes and returns the length of the list. To get from one node to the next in the list the node property self.next comes into play, and returns the link to the next node.
🌐
Real Python
realpython.com › linked-lists-python
Linked Lists in Python: An Introduction – Real Python
June 24, 2026 - Each element of a linked list is called a node, and every node has two different fields: Data contains the value to be stored in the node. Next contains a reference to the next node on the list.
🌐
Built In
builtin.com › data-science › python-linked-list
An Introduction to Python Linked List and How to Create One
We start by instantiating a new node, assigning the data to the new node, setting the next of the new node to the current head of the list, and then setting the head of the linked list to the new node. This makes the process nice and easy with low time complexity, compared to doing the same thing to a standard list in Python.
🌐
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 - We know that a node for a single linked list contains the item and the reference to the next node. Therefore, our node class will contain two member variables item and ref. The value of the item will be set by the value passed through the constructor, while the reference will be initially set to None: class Node: def __init__(self, data): self.item = data self.ref = None · Note: Additionally, you can define other methods besides the __init__()in the Node class, as we did in the "Linked Lists in Python" article.
Top answer
1 of 4
8

Just as mentioned by @abarnert , you always need a __iter__ method for the iterator class.

class LinkedListIterator:
    def __init__(self, head):
        self.current = head

    def __iter__(self):
        return self

    def __next__(self):
        if not self.current:
            raise StopIteration
        else:
            item = self.current.get_data()
            self.current = self.current.get_next()
            return item

class LinkedList:
    def __init__(self):
        self.head = None

    def __iter__(self):
        return LinkedListIterator(self.head)

    def add(self, item): 
        new_node = Node(item)
        new_node.set_next(self.head)
        self.head = new_node

Now that your class is iterable, you can use "for...in" loop:

test_list = LinkedList()
test_list.add(1)
test_list.add(2)
test_list.add(3)
for item in test_list:
    print(item)

Please check the tutorial here.

2 of 4
6

You can use the yield keyword to make a generator so you dont have to implement __next__()

class LinkedList:
    def __init__(self):
        self.head = None

    def __iter__(self):
        curNode = self.head
        while curNode:
            yield curNode.value
            curNode = curNode.nextNode

    def add(self, item): 
        new_node = Node(item)
        new_node.set_next(self.head)
        self.head = new_node

And in your print_iterator_explicit function you can do it like this

def print_iterator_explicit(items):       
    iterator = iter(ll)
    while True:
        try:
            print(next(iterator))
        except StopIteration:
            break

Check out this link for more information on iterators and generators: Iterators and generators

A little side note: your head variable is behaving like a tail. In a linked list the first node is called the head and the last is called the tail

🌐
PythonForBeginners
pythonforbeginners.com › home › linked list in python
Linked List in Python - PythonForBeginners.com
April 27, 2021 - To insert an element in a linked list at the end, we just have to find the node where the next element refers to None i.e. the last node. Then we create a new node with the given data and point the next element of the last node to the newly ...
🌐
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.
🌐
CodingNomads
codingnomads.com › data-structure-linked-list-python
Linked Lists in Python
Notice how the Node class contains an instance variable called next -- this is how one Node object links to another Node object. The next instance variable holds the reference to the next item in the list.
🌐
GitHub
github.com › OmkarPathak › Data-Structures-using-Python › blob › master › Linked Lists › SinglyLinkedList.py
Data-Structures-using-Python/Linked Lists/SinglyLinkedList.py at master · OmkarPathak/Data-Structures-using-Python
# Linked List and Node can be accomodated in separate classes for convenience · · class Node(object): # Each node has its data and a pointer that points to next node in the Linked List · def __init__(self, data, next = None): self.data = data; self.next = next; ·
Author: OmkarPathak
🌐
YouTube
youtube.com › watch
Understanding the next Attribute in Python Linked Lists
To learn more, please visit the YouTube Help Center: https://www.youtube.com/help
Published: May 25, 2025