How to Build a Linked List Node Class in Python

Create a Node class and a LinkedList class with insert, remove, and display methods to manage a singly linked list.

Medium Python 3.9+ Aug 9, 2026 OOP & classes 12 views 0 copies

Python code

50 lines
Python 3.9+
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

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

    def insert(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
        else:
            current = self.head
            while current.next:
                current = current.next
            current.next = new_node

    def remove(self, data):
        if not self.head:
            return False
        if self.head.data == data:
            self.head = self.head.next
            return True
        current = self.head
        while current.next:
            if current.next.data == data:
                current.next = current.next.next
                return True
            current = current.next
        return False

    def display(self):
        result = []
        current = self.head
        while current:
            result.append(current.data)
            current = current.next
        return result

if __name__ == "__main__":
    ll = LinkedList()
    ll.insert(10)
    ll.insert(20)
    ll.insert(30)
    print("After insert:", ll.display())
    print("Remove 20:", ll.remove(20))
    print("After remove:", ll.display())
    print("Remove 99:", ll.remove(99))

Output

stdout
After insert: [10, 20, 30]
Remove 20: True
After remove: [10, 30]
Remove 99: False

How it works

Each Node holds data and a reference to the next node. insert appends a new node at the tail by traversing to the last node. remove finds the first matching node and links the previous node to the next, effectively deleting it. The head pointer marks the start, ensuring updates when the head is removed. Display walks the chain and collects values. This classic OOP pattern mirrors how lists work under the hood in languages like C.

Common mistakes

  • Forgetting to update the head when removing the first node
  • Not handling an empty list before remove
  • Traversing past the end when current becomes None
  • Comparing data with `is` instead of `==`

Variations

  1. Use a sentinel node to simplify boundary cases
  2. Implement insert at head for O(1) prepend operations
  3. Make the class generic with type hints

Real-world use cases

  • Implementing internal data structures like LRU caches where fast head/tail operations matter
  • Managing undo/redo functionality in editors with a linked list of states
  • Building adjacency lists for graph traversal algorithms in memory-efficient ways

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.