Python Program to Implement a Linked List
Intermediate · Data structures
A linked list stores items in nodes, where each node holds a value and a link to the next node, and the last node links to nothing (None). Unlike a Python list, the items are not kept side by side, so adding or removing a node only changes a link. This program builds a singly linked list and shows adding, deleting, traversing and the empty list.
Program
Empty list: None After adding 10, 20, 30, 40: 10 -> 20 -> 30 -> 40 -> None After deleting 10 and 30: 20 -> 40 -> None Cannot delete 99 because it is not in the list
How it works
- Each
Nodeholds itsdataand anextlink, and the list itself only remembers its first node,head, which isNonewhile the list is empty. append()walks from the head along thenextlinks until it reaches the last node, then links the new node after it.delete()walks the list while remembering the node before the current one, and removes a node by linking that previous node straight to the node after it.- Deleting the head is a special case with no previous node, so the head simply moves on to the second node.
show()traverses the list from the head to the end, which is why an empty list prints justNone, and deleting a missing value prints a message instead of crashing.
Another way to write it
Insert at the front and search
Position of 20: 1 Position of 99: -1 (not found)
Adding at the front is the quickest insert, because the new node just points at the old first node and becomes the head, while a search has to follow the links one by one from the head.
Try it yourself
Add a length() method that walks the list and returns how many nodes it has.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises