Python Useful Tips — Linked List

Tony
6 min readNov 11, 2023

What is Linked List

In the context of Python, a linked list is a data structure that consists of a sequence of nodes. Each node contains data and a reference (or link) to the next node in the sequence. Unlike arrays or Python’s built-in list data type, linked lists do not provide constant-time access to individual elements. Instead, you must traverse the list node by node.

Python does not have a built-in linked list implementation since its built-in list (or dynamic array) is versatile and efficient for most use cases. However, it’s a common exercise to implement linked lists in Python to understand the concept.

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

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

def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node

def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next

# Usage:
llist = LinkedList()
llist.append("A")
llist.append("B")
llist.append("C")
llist.print_list() # Outputs: A B C

--

--