We know , The list method generally only supports the tail , for example pop、append, But for some queue problems , Need to operate on the head , You need to use pop(0)、insert(0,x) Other methods , Not very convenient ,Python Of collections Double ended queues in packets deque It solved the problem well , Added head method popleft、appendleft etc. .
from collections import deque
alist=['a','b','c','d']
dq=deque(alist)
print(dq.pop())
print(dq.popleft())
print(dq)
dq.appendleft('e')
print(dq)
Output :
d
a
deque(['b', 'c'])
deque(['e', 'b', 'c'])