Open In App

Python Library for Linked List

Last Updated : 10 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 points to the record that comes after it, this goes on until the end of the structure) rather than being tightly packed.

There are two types of linked list:

  1. Single-Linked List: In this, the nodes point to the node immediately after it
  2. Doubly Linked List: In this, the nodes not only reference the node next to it but also the node before it.

Linked List in Python:

To start with Python, it does not have a linked list library built into it like the classical programming languages. Python does have an inbuilt type list that works as a dynamic array but its operation shouldn’t be confused with a typical function of a linked list. This doesn’t mean one cannot implement a linked list in Python, they can but it will not be straight up. The following methods can be used to implement a linked list in Python since it does not have an inbuilt library for it:

Method 1: Using deque() package.
This is an inbuilt class in Python, obviously used for dequeue but can be implemented in such a way that it works like a linked list under certain conditions. 

Below is the implementation of the linked list:

Python3




# importing module
import collections
  
# initialising a deque() of arbitrary length
linked_lst = collections.deque()
  
# filling deque() with elements
linked_lst.append('first')
linked_lst.append('second')
linked_lst.append('third')
  
print("elements in the linked_list:")
print(linked_lst)
  
# adding element at an arbitrary position
linked_lst.insert(1, 'fourth')
  
print("elements in the linked_list:")
print(linked_lst)
  
# deleting the last element
linked_lst.pop()
  
print("elements in the linked_list:")
print(linked_lst)
  
# removing a specific element
linked_lst.remove('fourth')
  
print("elements in the linked_list:")
print(linked_lst)


 Output:

elements in the linked_list:
deque(['first', 'second', 'third'])
elements in the linked_list:
deque(['first', 'fourth', 'second', 'third'])
elements in the linked_list:
deque(['first', 'fourth', 'second'])
elements in the linked_list:
deque(['first', 'second'])

When to use deque() as a linked list?

  • Inserting and deleting elements at front and back respectively is the only need. Inserting and removing elements from the middle becomes time-consuming.
  • In-place reversal since Python now allows elements to be reversed in the place itself.
  • Storage is preferred over performance and not all elements get a separate node of their own

Method 2: Using llist package.

The llist is an extension module for CPython providing basic linked list data structures. The type is given below command in your command line: 

pip install llist

Below is the implementation of the linked list:

Python3




# importing packages
import llist
from llist import sllist,sllistnode
  
# creating a singly linked list
lst = sllist(['first','second','third'])
print(lst)
print(lst.first)
print(lst.last)
print(lst.size)
print()
  
# adding and inserting values
lst.append('fourth')
node = lst.nodeat(2)
  
lst.insertafter('fifth',node)
  
print(lst)
print(lst.first)
print(lst.last)
print(lst.size)
print()
  
# popping a value
#i.e. removing the last entry 
# of the list
lst.pop()
print(lst)
print(lst.first)
print(lst.last)
print(lst.size)
print()
  
# removing a specific element
node = lst.nodeat(1)
lst.remove(node)
print(lst)
print(lst.first)
print(lst.last)
print(lst.size)
print()


 Output: 

sllist([first, second, third])
sllistnode(first)
sllistnode(third)
3

sllist([first, second, third, fifth, fourth])
sllistnode(first)
sllistnode(fourth)
5

sllist([first, second, third, fifth])
sllistnode(first)
sllistnode(fifth)
4

sllist([first, third, fifth])
sllistnode(first)
sllistnode(fifth)
3

Method 3: Using StructLinks package

StructLinks is used to easily Access and visualize different Data structures including Linked lists, Doubly Linked lists, Binary trees, Graphs, Stacks, and Queues.

The structlinks.LinkedList and structlinks.DoublyLinkedList modules could be used to make linked lists. All the operations that could be performed with a list could also be performed with structlinks.LinkedList class.

Click to go to the documentation 

Type the command in your command line:

pip install structlinks

Below is the implementation of some methods of the linked list:

Python3




import structlinks
from structlinks import LinkedList
  
# create an empty linked list
lst = LinkedList()
  
# create a linked list with initial values
lst = LinkedList([1, 10.0, 'string'])
  
print(lst)
  
print()
  
print('Elements of list:')
  
# elements of the list
element0 = lst[0]
element1 = lst[1]
element2 = lst[2]
  
print(f'first element : {element0}')
print(f'second element : {element1 }')
print(f'third element : {element2}')
  
print()
  
print('Length of list:')
  
# Length of the list
length = len(lst)
  
print(f'size of the list : {length}')
  
print()
  
print('Set item:')
  
# Set item
lst[0] = 10
  
print(f'list after setting lst[0] to 10 : {lst}')
  
print()
  
print('Append And Insert:')
  
# Append And Insert
lst.append('another string')
lst.insert(1, 0.0)
  
print(f'list after appending and inserting: {lst}')
  
print()
  
print('Pop and Remove')
  
# Pop and Remove 
element = lst.pop(0)
lst.remove(10.0)
  
print(f'list after popping and removing : {lst}')
print(f'pop function also returns the element : {element}')
  
# This code is contributed by eeshannarula29


Output: 

[1 -> 10.0 -> string]

Elements of list:
1
10.0
string

Length of list:
3

Set item:
list after setting lst[0] to 10 : [10 -> 10.0 -> string]

Append and Insert:
list after appending and inserting: [10 -> 0.0 -> 10 -> string -> another string]

Pop and Remove:
list after popping and removing: [0.0 -> string -> another string]


Previous Article
Next Article

Similar Reads

Create Homogeneous Graphs using dgl (Deep Graph Library) library
In this article, we will create Homogeneous Graphs using dgl (Deep Graph Library) library. Graphs are nothing but collections of Nodes/Vertices and Edges. Also, Edges are nothing but Source nodes to Destination nodes. So all edges can be represented as (U, V) where U and V are nodes. G = (V, E) Package Required pip install dglWhat is Deep Graph Lib
3 min read
Linked list using dstructure library in Python
Dstructure is a Python library for creating data structures like linked list, stack, queue, hashmap, tree, etc. A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image: pip install dstructure Let's see how to cr
4 min read
Python Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The
3 min read
Generate Linked List consisting of maximum difference of squares of pairs of nodes from given Linked List
Given a Linked List of even number of nodes, the task is to generate a new Linked List such that it contains the maximum difference of squares of node values in decreasing order by including each node in a single pair. Examples: Input: 1 -> 6 -> 4 -> 3 -> 5 ->2Output: 35 -> 21 -> 7Explanation:The difference between squares of 6
11 min read
Remove all occurrences of one Linked list in another Linked list
Given two linked lists head1 and head2, the task is to remove all occurrences of head2 in head1 and return the head1. Examples: Input: head1 = 2 -> 3 -> 4 -> 5 -> 3 -> 4, head2 = 3 -> 4Output: 2 -> 5Explanation: After removing all occurrences of 3 -> 4 in head1 output is 2 -> 5. Input: head1 = 3 -> 6 -> 9 -> 8 -
9 min read
When is Doubly Linked List more Efficient than Singly Linked List?
Did you know there are some cases where a Doubly Linked List is more efficient than a Singly Linked List, even though it takes more memory compared to a Singly Linked List? What are those Cases? Well, we will discuss that in the following article, But first, let's talk about Singly and linked lists: What is a Singly Linked List?A singly linked list
4 min read
XOR Linked List - Reverse a Linked List in groups of given size
Given a XOR linked list and an integer K, the task is to reverse every K nodes in the given XOR linked list. Examples: Input: XLL = 7< – > 6 < – > 8 < – > 11 < – > 3, K = 3 Output: 8 < – > 6 < – > 7 < – > 3 < – > 11 Explanation: Reversing first K(= 3) nodes modifies the Linked List to 8 < – > 6
13 min read
XOR Linked List: Remove last node of the Linked List
Given an XOR linked list, the task is to delete the node at the end of the XOR Linked List. Examples: Input: 4<–>7<–>9<–>7Output: 4<–>7<–>9Explanation: Deleting a node from the end modifies the given XOR Linked List to 4<–>7<–>9 Input: 10Output: List is emptyExplanation: After deleting the only node present
15+ min read
XOR Linked List - Pairwise swap elements of a given linked list
Given a XOR linked list, the task is to pairwise swap the elements of the given XOR linked list . Examples: Input: 4 <-> 7 <-> 9 <-> 7Output: 7 <-> 4 <-> 7 <-> 9Explanation:First pair of nodes are swapped to formed the sequence {4, 7} and second pair of nodes are swapped to form the sequence {9, 7}. Input: 1 <
12 min read
Linked List of Linked List
Linked list of linke­d list, also known as nested linke­d lists, is a type of Linked List where each main node stores another full linked list. This structure­ beats old, plain linked lists. It gives way more­ flexibility to store and manage comple­x data. In this article we will learn about the basics of Linked List of Linked List, how to create L
9 min read