Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
llist module in Python
The llist module provides efficient linked list data structures for Python. Unlike Python's built-in lists, linked lists excel at insertions and deletions in large datasets by avoiding the need to shift elements.
Installation
Install the llist module using pip −
pip install llist
Singly Linked List (sllist)
A singly linked list where each node points to the next node. Here's how to create and manipulate one −
from llist import sllist
# Create a singly linked list
sll = sllist()
# Add elements
sll.append('Python')
sll.append('Java')
sll.append('JavaScript')
print(sll)
sllist(['Python', 'Java', 'JavaScript'])
Removing Elements
Remove elements using the remove() method with a node reference −
from llist import sllist sll = sllist(['Python', 'Java', 'JavaScript']) sll.remove(sll.nodeat(1)) # removes 'Java' at index 1 print(sll)
sllist(['Python', 'JavaScript'])
Doubly Linked List (dllist)
A doubly linked list where each node has references to both previous and next nodes −
from llist import dllist
# Create a doubly linked list
dll = dllist()
# Add elements
dll.append('C')
dll.append('C++')
dll.append('C#')
print(dll)
dllist(['C', 'C++', 'C#'])
Removing Elements from dllist
from llist import dllist dll = dllist(['C', 'C++', 'C#']) dll.remove(dll.nodeat(2)) # removes 'C#' at index 2 print(dll)
dllist(['C', 'C++'])
Performance Comparison
For large datasets, llist significantly outperforms Python's built-in list for insertions −
import time
from llist import sllist
# Python list - O(n) insertion in middle
py_list = list(range(100000))
start = time.time()
py_list.insert(len(py_list)//2, 'middle')
py_time = time.time() - start
# llist - O(1) insertion at known position
ll = sllist(range(100000))
start = time.time()
ll.insertbefore('middle', ll.nodeat(len(ll)//2))
ll_time = time.time() - start
print(f'Python list: {py_time:.6f} seconds')
print(f'llist: {ll_time:.6f} seconds')
Key Methods
| Method | Description | Both sllist/dllist |
|---|---|---|
append(item) |
Add item to end | Yes |
appendleft(item) |
Add item to beginning | Yes |
nodeat(index) |
Get node at index | Yes |
remove(node) |
Remove specific node | Yes |
When to Use llist
Use llist when you need −
- Frequent insertions/deletions in large datasets
- Memory-efficient operations on sequential data
- O(1) insertion/deletion at known positions
Stick with Python lists for small datasets or when you need random access by index.
Conclusion
The llist module provides efficient linked list implementations that excel at insertions and deletions in large datasets. Use sllist for simple forward traversal or dllist when you need bidirectional navigation.
