Doubly Linked List (deque)¶

Links in each node of a doubly linked list point to both the previous and the next node in the list. You can either use deque or write your own implementation.

In [6]:
from collections import deque
d = deque([1, 2, 3, 4], maxlen=1000)  # It's always better to choose the list length yourself using the maxlen argument, this will help avoid unpleasant surprises

d.append(5)  # Add an element to the list on the right
d.appendleft(0)  # Add an element to the list on the left

d.extend([6, 7])  # Extend the list on the right
d.extendleft([-1, -2])  # Extend the list on the left
print(d)

a = d.pop()  # Return and remove an element from the right. May raise IndexError
b = d.popleft()  # Return and remove an element from the left. May raise IndexError

print(a)
print(b)
print(d)
deque([-2, -1, 0, 1, 2, 3, 4, 5, 6, 7], maxlen=1000)
7
-2
deque([-1, 0, 1, 2, 3, 4, 5, 6], maxlen=1000)