Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To implement a singly linked list in Python, define a Node that stores a value and a reference to the next node, then define a list class that tracks at least head. Keep a tail reference when you need constant-time appends, and maintain a size counter if callers need the length without traversing the chain.

The implementation below is complete enough for learning and small specialized structures: it supports append, prepend, search, insertion after a known node, removal, iteration, length checks, and invariant validation. It also makes empty-list behavior explicit instead of leaving edge cases to chance.

How a linked list works

A singly linked list is a chain of nodes. Each node has two fields:

  • value: the payload, such as an integer, string, or object.
  • next: a reference to the next node, or None for the final node.

The list object stores a reference to the first node in head. A practical implementation also stores tail, pointing to the final node, and size, recording how many nodes are present.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Unlike a Python list, a linked list does not keep elements in one contiguous array. To reach the fifth element, Python must follow four next references. That is why traversal, search, and index lookup are linear operations.

A complete singly linked-list implementation

This version uses the following policies: find returns a node or None; remove returns a Boolean; removing from an empty list returns False; and inserting after a node that is not in the list raises ValueError. Documenting these choices is important because empty operations otherwise tend to produce inconsistent APIs.

class Node:
    def __init__(self, value, next_node=None):
        self.value = value
        self.next = next_node

    def __repr__(self):
        return f"Node({self.value!r})"


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

    def __len__(self):
        return self.size

    def __iter__(self):
        current = self.head
        while current is not None:
            yield current.value
            current = current.next

    def __contains__(self, value):
        return self.find(value) is not None

    def __repr__(self):
        values = ", ".join(repr(value) for value in self)
        return f"LinkedList([{values}])"

    def append(self, value):
        """Add value at the end in O(1) time."""
        node = Node(value)
        if self.head is None:
            self.head = self.tail = node
        else:
            self.tail.next = node
            self.tail = node
        self.size += 1

    def prepend(self, value):
        """Add value at the beginning in O(1) time."""
        node = Node(value, self.head)
        self.head = node
        if self.tail is None:
            self.tail = node
        self.size += 1

    def find(self, value):
        """Return the first matching Node, or None."""
        current = self.head
        while current is not None:
            if current.value == value:
                return current
            current = current.next
        return None

    def insert_after(self, node, value):
        """Insert value after node and return the new Node."""
        if node is None:
            raise ValueError("node must not be None")

        current = self.head
        while current is not node:
            if current is None:
                raise ValueError("node does not belong to this list")
            current = current.next

        new_node = Node(value, node.next)
        node.next = new_node
        if self.tail is node:
            self.tail = new_node
        self.size += 1
        return new_node

    def pop_front(self):
        """Remove and return the first value, or None when empty."""
        if self.head is None:
            return None

        removed = self.head
        self.head = removed.next
        removed.next = None
        self.size -= 1
        if self.head is None:
            self.tail = None
        return removed.value

    def remove(self, value):
        """Remove the first matching value and return True if removed."""
        previous = None
        current = self.head

        while current is not None:
            if current.value == value:
                if previous is None:
                    self.head = current.next
                else:
                    previous.next = current.next

                if self.tail is current:
                    self.tail = previous
                current.next = None
                self.size -= 1
                if self.size == 0:
                    self.head = self.tail = None
                return True

            previous, current = current, current.next

        return False

    def clear(self):
        """Detach every node and reset the list."""
        current = self.head
        while current is not None:
            following = current.next
            current.next = None
            current = following
        self.head = self.tail = None
        self.size = 0

    def check_invariants(self):
        """Raise AssertionError if internal links and metadata disagree."""
        if self.size == 0:
            assert self.head is None and self.tail is None
            return True

        assert self.head is not None and self.tail is not None
        count = 0
        current = self.head
        last = None
        while current is not None:
            count += 1
            last = current
            current = current.next
        assert count == self.size
        assert last is self.tail
        assert self.tail.next is None
        return True

Save the code in a file such as linked_list.py. It uses only the Python standard language features and runs on current Python 3 versions.

Why the endpoint updates matter

Appending to an empty list must set both head and tail. Prepending to a non-empty list changes only head; prepending to an empty list must also initialize tail. Removing the only node must clear both references. Removing the tail must move tail to the predecessor and set its next to None. The size counter must change exactly once for every successful insertion or removal.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why insert_after accepts a node

Once a caller already has a predecessor node, insertion requires changing two references: the new node points to the old successor, and the predecessor points to the new node. The pointer changes are constant time. This method still verifies membership by traversal, because accepting an arbitrary node from another list would corrupt this list’s chain.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Using the class

from linked_list import LinkedList

numbers = LinkedList()
print(numbers.pop_front())       # None

numbers.append(10)
numbers.append(30)
numbers.prepend(5)

middle = numbers.find(10)
numbers.insert_after(middle, 20)

print(list(numbers))             # [5, 10, 20, 30]
print(len(numbers))              # 4
print(numbers.tail.value)        # 30
print(numbers.remove(5))         # True
print(numbers.remove(999))       # False
print(list(numbers))             # [10, 20, 30]

numbers.check_invariants()       # True

Iteration is implemented with a generator, so ordinary constructs such as for value in numbers, list(numbers), and membership checks work without exposing pointer manipulation to every caller.

Operation complexity

With both head and tail, the common operations have these asymptotic costs:

Operation Singly linked list Python list collections.deque
Indexing O(n) traversal O(1) O(1) at ends; slower in the middle
Prepend O(1) O(n) because elements shift Approximately O(1) with appendleft
Append O(1) with tail; O(n) without it Amortized O(1) Approximately O(1)
Search O(n) O(n) O(n)
Remove after predecessor is known O(1) Usually requires shifting Endpoint operations are approximately O(1)

The costs describe the number of link or element operations as the structure grows. They do not mean every operation takes the same wall-clock time: a Python node is a separate object, and pointer-heavy traversal can have more allocation and cache overhead than traversing a compact array.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why search and indexing are linear

A linked list has no direct address calculation for position i. Starting at head, code must follow one link at a time until it reaches that position or the end. Keeping a size field makes len(numbers) constant time, but it does not make indexing or searching constant time.

Why a tail reference changes append

Without tail, append must walk from head to the final node, which is O(n). With tail, append sets tail.next, moves tail, and increments size, all in O(1). The trade-off is an additional invariant to maintain during every mutation.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Linked list, Python list, or deque?

Choose based on the operations your workload actually performs rather than on the data structure’s name.

Choose Best fit Reason Main limitation
Custom linked list Teaching links, node-based algorithms, or code that already holds node references Insertion or removal after a known node changes a few references Linear indexing, object overhead, and more invariants to maintain
Python list Random access, compact storage, sorting, slicing, and cache-friendly iteration Contiguous references provide O(1) indexing Inserting or deleting near the front or middle shifts references
collections.deque Production queues, stacks, and double-ended workloads Designed for approximately O(1) appends and pops at either end It is not intended to provide fast middle indexing or arbitrary node references

Python’s tutorial recommends collections.deque for queues because it is designed for fast appends and pops from both ends. The collections documentation describes approximately O(1) performance in either direction for endpoint operations. CPython’s FAQ describes lists as variable-length arrays backed by a contiguous array of references, not linked lists.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A queue example with the standard library

from collections import deque

queue = deque()
queue.append("first")
queue.append("second")
print(queue.popleft())  # first

Use the custom class when the educational or algorithmic purpose is the linked structure itself. For ordinary application queues, a deque normally avoids unnecessary Python-level node objects.

Testing the edge cases

Linked lists often fail at transitions between zero, one, and two nodes. Include tests for each mutation boundary:

def test_linked_list():
    linked = LinkedList()
    assert len(linked) == 0
    assert linked.head is None and linked.tail is None
    assert linked.pop_front() is None
    assert linked.remove("missing") is False

    linked.append("only")
    assert linked.head is linked.tail
    assert linked.pop_front() == "only"
    assert len(linked) == 0
    linked.check_invariants()

    linked.append("a")
    linked.append("b")
    linked.prepend("start")
    assert list(linked) == ["start", "a", "b"]

    assert linked.remove("start") is True       # head removal
    assert linked.remove("b") is True           # tail removal
    assert list(linked) == ["a"]
    assert linked.remove("a") is True           # final node
    linked.check_invariants()

    linked.append(1)
    linked.append(1)
    assert linked.remove(1) is True              # removes first duplicate only
    assert list(linked) == [1]

    linked.clear()
    assert len(linked) == 0
    linked.check_invariants()


test_linked_list()
  • Empty list: verify head, tail, and size agree.
  • One node: removing it must clear both endpoint references.
  • Head removal: the second node becomes the head.
  • Tail removal: the predecessor becomes the tail and its next is None.
  • Duplicate values: decide whether removal means the first match, all matches, or a specific node; this implementation removes the first match.
  • Repeated operations: run alternating appends, prepends, removals, and clears, checking invariants after each mutation.

Common implementation problems and fixes

Append becomes slow

Symptom: repeatedly appending takes progressively longer. Cause: the implementation searches for the final node every time. Fix: maintain tail and update it when appending, removing the tail, or removing the last remaining node.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

The list loses its last node

Symptom: iteration stops early after insertion. Cause: a new node was assigned to current.next before its old successor was saved. Fix: construct the new node with next_node=current.next, then assign current.next = new_node.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Tail points into the middle

Symptom: later appends overwrite or bypass nodes. Cause: removing the tail did not move tail to its predecessor. Fix: track previous during traversal and assign self.tail = previous when the removed node is the tail.

An infinite loop appears during iteration

Symptom: a loop never reaches None. Cause: a link points back to an earlier node, often because of accidental reuse of a node or a faulty insertion. Fix: run check_invariants, inspect each next assignment, and add cycle detection if your application permits externally supplied nodes.

Removing by value is unexpectedly expensive

Symptom: remove(value) is slow for large lists. Cause: finding the value is O(n), even though changing links after the predecessor is known is O(1). Fix: retain the node and its predecessor when your algorithm already has them, or use a different structure when fast lookup is the primary requirement.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Useful extensions

Index-based access

You can add get(index) by rejecting negative or out-of-range indexes and traversing until the requested position. Its time complexity remains O(n). Do not present it as equivalent to Python-list indexing.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Doubly linked lists

A doubly linked node adds a prev reference. That enables backward traversal and simpler removal when you already hold a node, but every insertion and deletion must update both directions. It also consumes more memory and creates more invariants.

Circular linked lists

A circular list points the final node back to the head instead of using None as a terminator. Traversal must stop after a known number of nodes or when it returns to the starting node; ordinary while current is not None loops are unsafe.

Memory and ownership

Each node is a Python object, so a custom linked list generally uses more memory than a Python list holding the same values. If nodes are exposed to callers, document who may mutate next; unrestricted external mutation can invalidate tail and size. Keeping mutation methods on the list object and validating invariants during tests is safer.

Or skip the browser setup

If you are publishing documentation or examples for this implementation and need a rendered page image, ScreenshotNeo provides a one-request screenshot API. It accepts consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python:

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://screenshotneo.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

cURL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://screenshotneo.com -o shot.webp

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://screenshotneo.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

See the ScreenshotNeo API documentation for capture options. Every plan includes features such as full-page and element captures, device presets, custom CSS and JavaScript, waiting rules, headers and cookies, PDF output, caching, signed links, asynchronous jobs, bulk capture, and a usage API. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to try it.

Final decision guide

  • Implement a custom linked list when learning pointer updates, experimenting with node-based algorithms, or operating on node references you already hold.
  • Use a Python list when indexing, slicing, compact storage, and iteration speed matter.
  • Use collections.deque for production queues, stacks, and operations at both ends.
  • Regardless of the structure, test empty, single-node, endpoint-removal, duplicate-value, and repeated-mutation cases.

Frequently Asked Questions

Can I make a linked list support negative indexes like a Python list?

Yes, but you must define the behavior yourself. A negative index requires knowing the length and then traversing to the corresponding node, so it remains O(n); it does not gain Python-list-style constant-time access.

How can I reverse a singly linked list in place?

Walk through the chain while retaining the next node, point the current node backward to the previous node, then advance both pointers. At the end, make the old tail the new head and the old head the new tail.

Should node attributes be public?

Public attributes keep a teaching implementation clear. In production code, restrict mutation or expose methods if callers changing next directly could break endpoint and size invariants.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What is the safest way to detect a cycle?

Use two pointers moving at different speeds (a slow pointer advancing one node and a fast pointer advancing two). If they meet, a cycle exists; if the fast pointer reaches None, the chain is acyclic.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.