Deque in Python with an example
Hey coder! In this tutorial, we are going to learn how to implement deque in Python using some simple operations.
Deque stands for Doubly Ended Queue where we can add and delete the elements from both ends.
So, we are here to learn how to add an element towards the right and towards the left of the list and also how to remove an element from the beginning and from the end of the list.
Operations Used for Deque
- append(): This method is used to place a new element at the last. We only need to pass a single parameter to this method. The time complexity of this method in the worst case is O(1).
For Example: list_name.append(element) - pop(): pop() operation is used to pop/remove an element from the list. We need to pass the index of the element we need to delete, by not passing any parameters, by default the last element will be removed.
For Example: list_name.pop(index) - insert(): This method is used to insert the new element at a specified position, here, we need to pass 2 parameters, index as well as the element you want to insert.
For Example: list_name.insert(index,element)
Let us dive into the program
Program: Deque
Let us take a non-empty list, then we can perform deque operations on it.
# Initialize an array arr1 = [2,8,-17,'Hello'] # INSERTION arr1.append(21) print('The modified arr1 after appending at last : ') print(arr1) arr1.insert(0,'c') print('The modified arr1 after appending at beginning : ') print(arr1) # DELETION arr1.pop() print('The modified arr1 after deleting at last : ') print(arr1) arr1.pop(0) print('The modified arr1 after deleting at beginning : ') print(arr1)
Output
The modified arr1 after appending at last : [2,8,-17,'Hello',21] The modified arr1 after appending at beginning : ['c',2,8,-17,'Hello',21] The modified arr1 after deleting at last : ['c',2,8,-17,'Hello'] The modified arr1 after deleting at beginning : [2,8,-17,'Hello']
In the Output, we can notice the changes that happened after performing the deque operations.
I hope, you are clear on how to implement Deque in python.
Thank you, keep solving keep learning.
Some of the related articles for you:
Leave a Reply