How to Handle a Deque in Python
Deques are a great way to handle memory efficient appends to a list-like object, it is a special module that allows you to handle list items in a more appropriate way.
![]()
Create a deque
To create a list simply import the deque module from collections library and call deque(_items_) on a variable.
from collections import deque |
Or if you wish to create an empty deque.
dq = deque() |
What happens if you want to create a deque of integers?
dq = deque(123) |
You simply can’t. Why is that? Because Integers are not iterable in python but String are.
This is because Integers, unlike strings, don’t have a __iter__ method and therefore they don’t return iterables.
str.__iter__ |
Accessing items by index
We can access items in a deque with an index number.
dq[0] |
Converting an item to integer
You can convert an item to a item simply by wrapping them around an int() method.
one = int(dq[0]) |
Appending items to a deque
We can append new items to our deque, to either left side or right side.
dq.append('4') |
Extending our deque
We can also add multiple values at once.
dq.extend('567') |
Popping items
We can delete items in both sides.
dq.pop() |
Rotating items
Or rotate our items if we want.
dq.rotate(-2) |
dq.rotate(2) |
Slicing deques
We cannot slice our deques, at least not directly.
dq[2:] |
You can import itertools and return a sliced list (not a deque) of items with islice() method.
import itertools |
You can find more information about deques in the official Python documentation: Deque Objects