In Python, there’s a specific object in the
collections module that you can use for linked lists, called
deque. This stands for double-ended queue.
collections.deque uses an implementation of a linked list in which you can access, insert, or remove elements from the beginning or end of the list with constant O(1) performance.
If we want to create a linked list with elements, we just need to supply an iterable object, like this. Here, I’m using the list, but you can supply any iterable object you want, such as the string. I’ll create a new variable called
llist, which will store a linked list of individual characters.
.pop() is interesting because it not only removes the rightmost element from the list but it also returns it. I’ll inspect
llist once more, and you can see that it no longer contains
'f'. We also have access to methods for appending and popping from the leftmost side of the list.
Become a Member to join the conversation.