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()
dq
deque([])
What happens if you want to create a deque of integers?123) dq = deque(
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
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__
<slot wrapper '__iter__' of 'str' objects>
int.__iter__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'int' has no attribute '__iter__'
Accessing items by index
We can access items in a deque with an index number.
0] dq[ |
Converting an item to integer
You can convert an item to a item simply by wrapping them around an int()
method.
0]) one = int(dq[ |
Appending items to a deque
We can append new items to our deque, to either left side or right side.
'4') dq.append( |
Extending our deque
We can also add multiple values at once.
'567') dq.extend( |
Popping items
We can delete items in both sides.
dq.pop() |
Rotating items
Or rotate our items if we want.
-2) dq.rotate( |
2) dq.rotate( |
Slicing deques
We cannot slice our deques, at least not directly.
2:] dq[ |
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