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.
With double-ended what I really mean is that we can append elements from either end (start and end) and remove them from either end (start and end).
To implement this we can use deque from collections module in Python just like we did in Queue.
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'])
That’s it! I hope you understood easily. See you in the next tutorial!
Lectures
Lecture 1: https://medium.com/@saifmdco/data-structures-with-python-introduction-4dadeffa2215
Lecture 2: https://medium.com/@saifmdco/data-structures-with-python-arrays-c498518bf7fd
Lecture 3: https://medium.com/@saifmdco/data-structures-in-python-lists-653a3ad103ab
Lecture 4: https://medium.com/@saifmdco/data-structures-in-python-tuples-3c350640cd9a
Lecture 5: https://medium.com/@saifmdco/data-structures-in-python-dictionary-fad27ffdda8b
Lecture 6: https://medium.com/@saifmdco/data-structures-in-python-2d-array-6bc0154aa717
Lecture 7: https://medium.com/@saifmdco/data-structures-in-python-matrix-22adba5aa597
Lecture 8: https://medium.com/@saifmdco/data-structures-in-python-sets-92d5445e97e8
Lecture 9: https://medium.com/@saifmdco/data-structures-in-python-chainmap-fca2a9d47249
Lecture 10: https://medium.com/@saifmdco/data-structures-in-python-linkedlist-50f2118c659e
Lecture 11: https://medium.com/@saifmdco/data-structures-in-python-stack-6bf182d63581
Lecture 12: https://medium.com/@saifmdco/data-structures-in-python-queue-6361d3dcff0
Lecture 13: https://medium.com/@saifmdco/data-structures-in-python-dequeue-1a585e269a55
Lecture 14: https://medium.com/@saifmdco/data-structures-in-python-custom-stack-b7b9173b4eae
Lecture 15: https://medium.com/@saifmdco/data-structures-in-python-hash-table-39be784eefc1
Lecture 16: https://medium.com/@saifmdco/data-structures-in-python-doubly-linked-list-fe698d74756c