Tech With Tim Logo
Go back

Collections/Deque(deck)

Deque(deck)

The collections module also contains support for the deque object. The deque object is typically used to perform fast operations on the beginning and and of a list. It should only be used when you care more about manipulating data and taking items from the beginning and end of the list rather than random lookups of elements.

To create a new deque we can do the following:

import collections
from collections import deque

d = deque("hello")  # Takes and iterable argument
print(d)  # prints deque(["h", "e", "l", "l","o"])

Manipulation

The deque object allows for appending to the beginning and end of the deque. It also allows us to pop elements from either end.

import collections
from collections import deque

d = deque("hello")  # Takes and iterable argument
d.appendleft(5)  # d is now deque([5, "h", "e", "l","l", "o"])
d.append(4)  # d is now deque([5, "h", "e", "l","l", "o", 4])

d.pop()  # would return 4
d.popleft()  # would return 5

More Methods

The deque object also has some other useful methods.

.clear(): This will empty the deque object.

import collections
from collections import deque

d = deque("hello")  # Takes and iterable d.clear()

print(d) # prints deque([])

.extend(iterable): This will add all of the items from the passed iterbale data type or collection to the end of the deque. .extendleft() words the same way

import collections
from collections import deque

d = deque("hello")  # Takes and iterable 
d.extend("12")
d.extend([7,8])
d.extendleft(100)

print(d) # prints deque([100,"h", "e", "l", "l", "o","1", "2", 7, 8])

.rotate(n): Given an int n this method will rotate the deck that many positions. The given int can be negative or positive. If it is negative it will rotate the deque to the left, otherwise it will rotate to the right.

import collections
from collections import deque

d = deque("hello")  # Takes and iterable 
d.rotate(1)

print(d) # prints deque(["o", "h", "e", "l", "l"])

d.rotate(-2)

print(d)  # prints deque(["e", "l", "l", "o", "h"])

If you benefited from these tutorials and appreciate the hard work I put into creating my videos and writing these guides please consider supporting me and the content. Any amount helps and your donations and support is what keeps techwithim.net up and running.

Design & Development by Ibezio Logo