head1node = head2while node.value != 7:3 node = node.next4head = Node(1, head)5new = Node(8, node.next)6node.next = new7old = head.next8head.next = old.nextprev3nextprev7nextprev9nextNoneprev1nextprev8nextnode
Nodes: a value part and a next part (a prev part when doubly linked)Arrows: the reference a link field holdsThe mint tag: the variable node during a walkEach node is a value plus a next link, drawn as an arrow on the table; head refers to the first node and None ends the list. Adding node 1 at the front, inserting 8 after 7 and removing 3 only swing arrows: no node moves. Prev arrows make the list doubly linked; pointing 9 back at 1 makes it circular.

Nodes and links

  1. A linked list keeps each item in its own small object called a node. A node holds two things: the value, here 3, and next, a reference (an arrow) to the node after it. Nodes can sit anywhere in memory.

Working on a list

Two more shapes

What happens

;; step 1/8 · node
class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next

Node(3) makes one node:
  value = 3
  next  = None until we link it
a reference is how Python names an object: an arrow, not a copy

Costs follow MIT 6.006 (Lecture 2): a singly linked list inserts and deletes at the front in Θ(1) but needs O(n) to get or set the item at position i. Inserting or removing after a node you already hold is O(1); finding that node is the O(n) part. Python's built-in list is an array of references, not a linked list: insert(0, x) and pop(0) move the other items, O(n). For fast adds and removes at both ends the standard library has collections.deque, which gives about O(1) appends and pops on either side.