Data Structures in Python: Dequeue

A Dequeue is simply a double-ended Queue.

If you don’t know what a Queue is then you must go through the Queue tutorial.

Adding elements to either end

We can add elements to the left using the ‘appendleft()’ method and to the right using the ‘append()’ method:

from collections import dequedequeue = deque(['Sun','Mon','Tue'])dequeue.appendleft('Thu') #Appending to leftprint(dequeue)#OUTPUT
deque(['Thu', 'Sun', 'Mon', 'Tue'])
dequeue.append('Fri') #Appending to right
print(dequeue)
#OUTPUT
deque(['Thu', 'Sun', 'Mon', 'Tue', 'Fri'])

Removing elements to either end

We can remove elements from the left using the ‘popleft()’ method and from the right using the ‘pop()’ method:

from collections import dequedequeue = deque(['Sun','Mon','Tue'])dequeue.popleft() #removing from leftprint(dequeue)#OUTPUT
deque(['Sun', 'Mon', 'Tue', 'Fri'])
dequeue.pop() #removing from right
print(dequeue)
#OUTPUT
deque(['Sun', 'Mon', 'Tue'])

Lectures

Lecture 1: https://medium.com/@saifmdco/data-structures-with-python-introduction-4dadeffa2215

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store