In this article, we will learn about the implementation of a linked list in Python. To implement the linked list in Python, we will use classes in Python. Now, we know that a linked list consists of nodes and nodes have two elements i.e. data and a reference to another node. Let’s implement the node first.
What is Linked List in Python
A linked list is a type of linear data structure similar to arrays. It is a collection of nodes that are linked with each other. A node contains two things first is data and second is a link that connects it with another node. Below is an example of a linked list with four nodes and each node contains character data and a link to another node. Our first node is where head points and we can access all the elements of the linked list using the head.
Linked List
Creating a linked list in Python
In this LinkedList class, we will use the Node class to create a linked list. In this class, we have an __init__ method that initializes the linked list with an empty head. Next, we have created an insertAtBegin() method to insert a node at the beginning of the linked list, an insertAtIndex() method to insert a node at the given index of the linked list, and insertAtEnd() method inserts a node at the end of the linked list. After that, we have the remove_node() method which takes the data as an argument to delete that node. In the remove_node() method we traverse the linked list if a node is present equal to data then we delete that node from the linked list. Then we have the sizeOfLL() method to get the current size of the linked list and the last method of the LinkedList class is printLL() which traverses the linked list and prints the data of each node.
Creating a Node Class
We have created a Node class in which we have defined a __init__ function to initialize the node with the data passed as an argument and a reference with None because if we have only one node then there is nothing in its reference.
Python
class Node:
def __init__(self, data):
self.data = data
self.next = None
Insertion in Linked List
Insertion at Beginning in Linked List
This method inserts the node at the beginning of the linked list. In this method, we create a new_node with the given data and check if the head is an empty node or not if the head is empty then we make the new_node as head and return else we insert the head at the next new_node and make the head equal to new_node.
Python
def insertAtBegin(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
else:
new_node.next = self.head
self.head = new_node
Insert a Node at a Specific Position in a Linked List
This method inserts the node at the given index in the linked list. In this method, we create a new_node with given data , a current_node that equals to the head, and a counter ‘position’ initializes with 0. Now, if the index is equal to zero it means the node is to be inserted at begin so we called insertAtBegin() method else we run a while loop until the current_node is not equal to None or (position+1) is not equal to the index we have to at the one position back to insert at a given position to make the linking of nodes and in each iteration, we increment the position by 1 and make the current_node next of it. When the loop breaks and if current_node is not equal to None we insert new_node at after to the current_node. If current_node is equal to None it means that the index is not present in the list and we print “Index not present”.
Python
# Method to add a node at any index
# Indexing starts from 0.
def insertAtIndex(self, data, index):
if (index == 0):
self.insertAtBegin(data)
return
position = 0
current_node = self.head
while (current_node != None and position+1 != index):
position = position+1
current_node = current_node.next
if current_node != None:
new_node = Node(data)
new_node.next = current_node.next
current_node.next = new_node
else:
print("Index not present")
Insertion in Linked List at End
This method inserts the node at the end of the linked list. In this method, we create a new_node with the given data and check if the head is an empty node or not if the head is empty then we make the new_node as head and return else we make a current_node equal to the head traverse to the last node of the linked list and when we get None after the current_node the while loop breaks and insert the new_node in the next of current_node which is the last node of linked list.
Python
def inserAtEnd(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
current_node = self.head
while(current_node.next):
current_node = current_node.next
current_node.next = new_node
Update the Node of a Linked List
This code defines a method called updateNode in a linked list class. It is used to update the value of a node at a given position in the linked list.
Python
# Update node of a linked list
# at given position
def updateNode(self, val, index):
current_node = self.head
position = 0
if position == index:
current_node.data = val
else:
while(current_node != None and position != index):
position = position+1
current_node = current_node.next
if current_node != None:
current_node.data = val
else:
print("Index not present")
Delete Node in a Linked List
Remove First Node from Linked List
This method removes the first node of the linked list simply by making the second node head of the linked list.
Python
def remove_first_node(self):
if(self.head == None):
return
self.head = self.head.next
Remove Last Node from Linked List
In this method, we will delete the last node. First, we traverse to the second last node using the while loop, and then we make the next of that node None and last node will be removed.
Python
def remove_last_node(self):
if self.head is None:
return
curr_node = self.head
while (curr_node.next != None and curr_node.next.next != None):
curr_node = curr_node.next
curr_node.next = None
Delete a Linked List Node at a given Position
In this method, we will remove the node at the given index, this method is similar to the insert_at_inded() method. In this method, if the head is None we simply return else we initialize a current_node with self.head and position with 0. If the position is equal to the index we called the remove_first_node() method else we traverse to the node just before the one we wanted to remove using the while loop. The loop continues until current_node is None or position reaches index – 1. After the loop, we check that if current_node or current_node.next is None. If current_node is None, it means the index is out of range. If not then we bypass the node to be removed.
Python
# Method to remove at given index
def remove_at_index(self, index):
if self.head is None:
return
current_node = self.head
position = 0
if index == 0:
self.remove_first_node()
else:
while current_node is not None and position < index - 1:
position += 1
current_node = current_node.next
if current_node is None or current_node.next is None:
print("Index not present")
else:
current_node.next = current_node.next.next
Delete a Linked List Node of a given Data
This method removes the node with the given data from the linked list. In this method, firstly we made a current_node equal to the head and run a while loop to traverse the linked list. This while loop breaks when current_node becomes None or the data next to the current node is equal to the data given in the argument. Now, After coming out of the loop if the current_node is equal to None it means that the node is not present in the data and we just return, and if the data next to the current_node is equal to the data given then we remove that node by making next of that removed_node to the next of current_node. And this is implemented using the if else condition.
Python
def remove_node(self, data):
current_node = self.head
# Check if the head node contains the specified data
if current_node.data == data:
self.remove_first_node()
return
while current_node is not None and current_node.next.data != data:
current_node = current_node.next
if current_node is None:
return
else:
current_node.next = current_node.next.next
Linked List Traversal in Python
This method traverses the linked list and prints the data of each node. In this method, we made a current_node equal to the head and iterate through the linked list using a while loop until the current_node become None and print the data of current_node in each iteration and make the current_node next to it.
Python
def printLL(self):
current_node = self.head
while(current_node):
print(current_node.data)
current_node = current_node.next
Get Length of a Linked List in Python
This method returns the size of the linked list. In this method, we have initialized a counter ‘size’ with 0, and then if the head is not equal to None we traverse the linked list using a while loop and increment the size with 1 in each iteration and return the size when current_node becomes None else we return 0.
Python
def sizeOfLL(self):
size = 0
if(self.head):
current_node = self.head
while(current_node):
size = size+1
current_node = current_node.next
return size
else:
return 0
Example of the Linked list in Python
In this example, After defining the Node and LinkedList class we have created a linked list named “llist” using the linked list class and then insert four nodes with character data ‘a’, ‘b’, ‘c’, ‘d’ and ‘g’ in the linked list then we print the linked list using printLL() method linked list class after that we have removed some nodes using remove methods and then print the linked list again and we can see in the output that node is deleted successfully. After that, we also print the size of the linked list.
Python
# Create a Node class to create a node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Create a LinkedList class
class LinkedList:
def __init__(self):
self.head = None
# Method to add a node at the beginning of the LL
def insertAtBegin(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
# Method to add a node at any index
# Indexing starts from 0.
def insertAtIndex(self, data, index):
if index == 0:
self.insertAtBegin(data)
return
position = 0
current_node = self.head
while current_node is not None and position + 1 != index:
position += 1
current_node = current_node.next
if current_node is not None:
new_node = Node(data)
new_node.next = current_node.next
current_node.next = new_node
else:
print("Index not present")
# Method to add a node at the end of LL
def insertAtEnd(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
current_node = self.head
while current_node.next:
current_node = current_node.next
current_node.next = new_node
# Update node at a given position
def updateNode(self, val, index):
current_node = self.head
position = 0
while current_node is not None and position != index:
position += 1
current_node = current_node.next
if current_node is not None:
current_node.data = val
else:
print("Index not present")
# Method to remove first node of linked list
def remove_first_node(self):
if self.head is None:
return
self.head = self.head.next
# Method to remove last node of linked list
def remove_last_node(self):
if self.head is None:
return
# If there's only one node
if self.head.next is None:
self.head = None
return
# Traverse to the second last node
current_node = self.head
while current_node.next and current_node.next.next:
current_node = current_node.next
current_node.next = None
# Method to remove a node at a given index
def remove_at_index(self, index):
if self.head is None:
return
if index == 0:
self.remove_first_node()
return
current_node = self.head
position = 0
while current_node is not None and current_node.next is not None and position + 1 != index:
position += 1
current_node = current_node.next
if current_node is not None and current_node.next is not None:
current_node.next = current_node.next.next
else:
print("Index not present")
# Method to remove a node from the linked list by its data
def remove_node(self, data):
current_node = self.head
# If the node to be removed is the head node
if current_node is not None and current_node.data == data:
self.remove_first_node()
return
# Traverse and find the node with the matching data
while current_node is not None and current_node.next is not None:
if current_node.next.data == data:
current_node.next = current_node.next.next
return
current_node = current_node.next
# If the data was not found
print("Node with the given data not found")
# Print the size of the linked list
def sizeOfLL(self):
size = 0
current_node = self.head
while current_node:
size += 1
current_node = current_node.next
return size
# Print the linked list
def printLL(self):
current_node = self.head
while current_node:
print(current_node.data)
current_node = current_node.next
# create a new linked list
llist = LinkedList()
# add nodes to the linked list
llist.insertAtEnd('a')
llist.insertAtEnd('b')
llist.insertAtBegin('c')
llist.insertAtEnd('d')
llist.insertAtIndex('g', 2)
# print the linked list
print("Node Data:")
llist.printLL()
# remove nodes from the linked list
print("\nRemove First Node:")
llist.remove_first_node()
llist.printLL()
print("\nRemove Last Node:")
llist.remove_last_node()
llist.printLL()
print("\nRemove Node at Index 1:")
llist.remove_at_index(1)
llist.printLL()
# print the linked list after all removals
print("\nLinked list after removing a node:")
llist.printLL()
print("\nUpdate node Value at Index 0:")
llist.updateNode('z', 0)
llist.printLL()
print("\nSize of linked list:", llist.sizeOfLL())
OutputNode Data
c
a
g
b
d
Remove First Node
Remove Last Node
Remove Node at Index 1
Linked list after removing a node:
a
b
Update node Value
z
b
Size of linked list : 2
Python Linked List – FAQs
What is a linked list in Python?
A linked list is a linear data structure where elements are stored in nodes. Each node contains data and a reference (or pointer) to the next node in the sequence. Unlike arrays, linked lists do not store elements in contiguous memory locations.
Does Python have a linked list library?
Python does not have a built-in linked list library in its standard library. However, linked lists can be implemented using classes and references in Python.
How to create a linked list?
You can create a linked list in Python by defining a Node class and a LinkedList class. Here’s a basic example of how to implement a linked list:
class Node:
def __init__(self, data):
self.data = data
self.next = None # Reference to the next node
# LinkedList class manages the nodes and operations of the linked list
class LinkedList:
def __init__(self):
self.head = None # Initialize an empty linked list
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):
current_node = self.head
while current_node:
print(current_node.data, end=" -> ")
current_node = current_node.next
print("None")
# Example usage:
llist = LinkedList()
llist.append(1)
llist.append(2)
llist.append(3)
llist.print_list()
Is Tuple a Linked list in Python?
No, a tuple is not a linked list in Python. Tuples are immutable sequences of elements stored in contiguous memory, whereas linked lists are mutable and elements are stored in separate nodes with references.
What are the types of linked list?
The main types of linked lists include:
- Singly Linked List: Each node points to the next node in the sequence.
- Doubly Linked List: Each node points to both the next and previous nodes.
- Circular Linked List: Last node points back to the first node, forming a circle.
- Sorted Linked List: Elements are stored in a sorted order based on a specific criterion.
Similar Reads
Singly Linked List in Python
A Singly Linked List is a type of data structure that is made up of nodes that are created using self-referential structures. Each node contains a data element and a reference (link) to the next node in the sequence. This allows for a dynamic and efficient management of data elements. Table of Conte
10 min read
Python Library for Linked List
Linked list is a simple data structure in programming, which obviously is used to store data and retrieve it accordingly. To make it easier to imagine, it is more like a dynamic array in which data elements are linked via pointers (i.e. the present record points to its next record and the next one p
5 min read
Python list() Function
Python list() function takes any iterable as a parameter and returns a list. In Python iterable is the object you can iterate over. Some examples of iterables are tuples, strings, and lists. Python list() Function SyntaxSyntax: list(iterable) Parameter: iterable: an object that could be a sequence (
4 min read
Python List of Lists
A list of lists in Python is a collection where each item is another list, allowing for multi-dimensional data storage. We access elements using two indices: one for the outer list and one for the inner list. In this article, we will explain the concept of Lists of Lists in Python, including various
3 min read
Python List Exercise
List OperationsAccess List ItemChange List itemReplace Values in a List in PythonAppend Items to a listInsert Items to a listExtend Items to a listRemove Item from a listClear entire listBasic List programsMaximum of two numbersWays to find length of listMinimum of two numbersTo interchange first an
3 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
5 min read
Update List in Python
In Python Programming, a list is a sequence of a data structure that is mutable. This means that the elements of a list can be modified to add, delete, or update the values. In this article we will explore various ways to update the list. Let us see a simple example of updating a list in Python. [GF
3 min read
Print lists in Python
Printing a list in Python is a common task when we need to visualize the items in the list. There are several methods to achieve this and each is suitable for different situations. In this article we explore these methods. The simplest way of printing a list is directly with the print() function: [G
3 min read
llist module in Python
Up until a long time Python had no way of executing linked list data structure. It does support list but there were many problems encountered when using them as a concept of the linked list like list are rigid and are not connected by pointers hence take a defined memory space that may even be waste
3 min read
Pretty print Linked List in Python
Creating custom data types can be tricky, especially when you want to use it like any other data type. Linked List can be thought of as an example of a custom data type. In other languages, if you want to print the linked list, you would define a separate print function, something like pprint but it
3 min read