Drawing diagrams helps. Here's your linked list:

[   ]
  |
  v
[   ]
  |
  V
[   ]
  |
  V
 None

Each arrow leading from a box represents the next attribute of that node.

Here are the three variables a, b, and c:

         [   ] <-- a
           |
           v
         [   ] <-- b
           |
           V
         [   ] <-- c
           |
           V
          None

Each of these variables also points to a particular node.

If you say b.next = None, the next attribute of the node referenced by b is modified, like this:

         [   ] <-- a
           |
           v
None <-- [   ] <-- b


         [   ] <-- c
           |
           V
          None

This modifies the structure of the list. If you just set b itself to a different value, though, this is what happens:

         [   ] <-- a
           |
           v
None <-- [   ]     b --> None


         [   ] <-- c
           |
           V
          None

You changed b, but the node that b used to point to stays right where it was. Note that this is similar to how the c node continued to exist even after you set b.next = None.

Answer from Samwise on Stack Overflow
🌐
LeetCode
leetcode.com › problems › design-linked-list
Design Linked List - LeetCode
If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list.
🌐
LeetCode
leetcode.com › discuss › general-discussion › 603729 › singly-linked-list-data-structure-python
Singly Linked List Data Structure - Python - Discuss - LeetCode
So linked list becomes 1 -> 7-> 8-> 6-> 4-> None llist.insert_after(llist.head.next, 8) print('Created linked list is:') llist.print_linked_list() # llist.delete_key(4) llist.delete_key_using_dummy(4) print('\nUpdated linked list is:') llist.print_linked_list() print('\nlength is : ') print(llist.length()) llist.delete_all_occurrences(4) print('\nUpdated linked list is:') llist.print_linked_list() print("\n\nIterative Search") print(llist.search_key(7)) print("\nRecursive Search ") print(llist.search_key_recursive(llist.head,7)) print("\n Search at Index") print(llist.get_at_index(4)) print("\
Discussions

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
python - Linked list problem (Leetcode) - understanding inputs - Stack Overflow
I am starting to complete some Leetcode problems, having finished an online Data Structures and Algorithms course, but I'm struggling to understand what some of the input variables represent. I've More on stackoverflow.com
🌐 stackoverflow.com
Linked list in python
man Linked list is nothing but a chain of classes connected with a next pointer. Use chatgpt to understand basics. Do some easy problems. It will click. You have got to put in the work More on reddit.com
🌐 r/leetcode
11
1
May 13, 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 ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/learnpython › please help me understanding linked list in python in leetcode
r/learnpython on Reddit: Please help me understanding Linked List in Python in LeetCode
April 8, 2023 -

Hello all,

I learned Data Structures in C, which I understood pretty good, but can't wrap around about them in Python as I am relatively new to DS in Python. I solved some DS questions in C before but I don't want to go back to C every time I get a DS problem. What needs to be done in this problem is to remove nth node from end of the linked list. What I wanted to do is to count total nodes and find the position from the start of the list and traverse two pointers, one which points the actual node to be bypassed/deleted and a previous node of which I will connect the "actual node"'s next node...but it doesn't seem to work.

Image for reference: https://ibb.co/jRy39k7

How I did is to make a curr pointer = head to count total nodes. After traversing, make a prev pointer = head and now set curr = head.next and traverse the list until the curr reaches the position required (which is given by i) and prev before curr.

Here are the things which I don't understand:

  1. From what I understand, after the second while loop breaks, the curr is at node 4 with value 4 (shown in left top image) and prev is at node 3 and both (I think) clearly has a attribute called "val" but why is there an error in the left? You can see the values being printed below too.

  2. You can also clearly see that there are only two print statements in the whole code but I am getting a total of 3 print outputs. Why is that?

Here's the code:

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:

        node_count = 0
        curr = head

        while True:
            if curr is None:
                break
            node_count += 1
            curr = curr.next
        
        i = node_count-n-1

        prev = head
        curr = head.next

        x = 0
        while True:
            if x >= i: break
            curr = curr.next
            prev = prev.next
            x += 1
        print(prev.val)
        print(curr.val)
        
        return head

NOTE:

  1. I clearly know that the code is incomplete, that I didn't actually delete the required node.

  2. There maybe a better solution than mine but right now, I am only concerned with code to be working without any errors.

  3. I have already tried using a for loop like for x in range(i) but same stuff.

Please help me, it would be a great favour.

Thank You

🌐
LeetCode
leetcode.com › problems › design-linked-list › discuss › 298681 › Doubly-Linked-List-Solution-in-Python
Doubly Linked List Solution in Python - Design ...
May 25, 2019 - 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.
🌐
LeetCode
leetcode.com › problem-list › linked-list
Problem List - LeetCode
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.
🌐
LeetCode
leetcode.com › explore › learn › card › linked-list
LeetCode - The World's Leading Online Programming Learning Platform
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.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 74359459 › linked-list-problem-leetcode-understanding-inputs
python - Linked list problem (Leetcode) - understanding inputs - Stack Overflow
I am starting to complete some Leetcode problems, having finished an online Data Structures and Algorithms course, but I'm struggling to understand what some of the input variables represent. I've included one of the solutions as an example. The problem gives me the head of a sorted linked list as input and asks me to remove all duplicates and return a new linked list as a solution.
🌐
AlgoMonster
algo.monster › home › 707. design linked list
707. Design Linked List - In-Depth Explanation
Why it matters: While Python's garbage collector will eventually clean up the node, explicitly setting node_to_delete.next = None is good practice as it: ... node_to_delete = predecessor.next predecessor.next = node_to_delete.next node_to_delete.next = None # Explicitly break the reference ... Linked List Cycle Given a linked list with potentially a loop determine whether the linked list from the first node contains a cycle in it For bonus points do this with constant space Parameters nodes The first node of a linked list with potentially a loop Result Whether there is a loop contained
🌐
GitHub
github.com › wonkwonlee › leetcode-python › blob › master › Linked-List › Linked-List.md
leetcode-python/Linked-List/Linked-List.md at master · wonkwonlee/leetcode-python
In most cases, we use head node (the first node) to represent the whole list. To access the i-th element, we have to traverse from the head node one by one. In the example above, the head is the node 23. The only way to visit the 3rd node is to use the "next" field of the head node, and then use the "next" field of the second node. It takes O(N) time on average to visit an element by an index, where N is the length of the linked list.
Author: wonkwonlee
🌐
LeetCode
leetcode.com › problems › merge-two-sorted-lists › solutions › 1827083 › python-list-linkedlist
Python | List <-> LinkedList - Merge Two Sorted Lists
March 7, 2022 - Can you solve this real interview question? Merge Two Sorted Lists - You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the ...
🌐
LeetCode
leetcode.com › discuss › study-guide › 1800120 › Become-Master-In-Linked-List
Become Master In Linked List - Discuss - LeetCode
Given :- -------- -------- -------- ... from linked list -------- -------- -------- -------- -------- | 5 | --> | 10 | --> | 15 | |-X- | 12 | |----> | 14 | --> X -------- -------- --------| -------- | -------- |-----------------| ... Problem list is in order from EASY to HARD in a sequence. And all question's are available on LeetCode...
🌐
LeetCode
leetcode.com › problems › linked-list-components
Linked List Components - LeetCode
Linked List Components - You are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values. Return the number of connected components in nums.
🌐
GitHub
github.com › kamyu104 › LeetCode-Solutions › blob › master › Python › linked-list-cycle.py
LeetCode-Solutions/Python/linked-list-cycle.py at master · kamyu104/LeetCode-Solutions
🏋️ Python / Modern C++ Solutions of All 3860 LeetCode Problems (Weekly Update) - LeetCode-Solutions/Python/linked-list-cycle.py at master · kamyu104/LeetCode-Solutions
Author: kamyu104
🌐
Medium
medium.com › javarevisited › 15-leetcode-problems-to-get-better-at-linked-list-4c5aa8cd4a11
15 LeetCode problems to get better at Linked List | by javinpaul | Javarevisited | Medium
May 18, 2025 - You can also join a website like AlgoMonster by ex-Google Engineers, or see a course like Grokking the Coding Interview: Patterns for Coding Questions from DeisgnGurus.io where you can learn coding patterns like fast and slow pointers which can be used to solve multiple Leetcode problem related to linked list. If you need recommendations, following are some of my the tried and tested resources to learn Data Structure and Algorithms in-depth: Data Structures and Algorithms: Deep Dive Using Java for Java developers · Algomonster, a coding interview website created by ex Google engineers to help you with cracking FAANG interviews. Algorithms and Data Structures in Python for those who love Python
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))
🌐
GitConnected
levelup.gitconnected.com › python-unleashed-cracking-the-leetcode-100-linked-list-part1-4e3e0f0b9d3
Python Unleashed: Cracking the LeetCode 100 — Linked List-Part: I | by Senthil E | Level Up Coding
July 30, 2023 - Question: What is a linked list? Answer: A linked list is a linear data structure where each element is a separate object. Each element (node) of a list is comprising of two items - the data and a reference to the next node. The last node has a reference to null.
🌐
GitHub
github.com › doocs › leetcode › blob › main › solution › 0700-0799 › 0707.Design Linked List › README_EN.md
leetcode/solution/0700-0799/0707.Design Linked List/README_EN.md at main · doocs/leetcode
The limit here is tiny, but repeated allocation dominates once the list grows large. Preallocate two arrays for values and successor indices, and treat an increasing · $\textit{idx}$ as a node pool. Inserting claims the next slot and rewrites indices—the same linking as pointers.
Author: doocs