TIL: Deque

Today I was solving Advent of Code, where in the first part I had to take elements one by one from a list and insert them into another one, so I used pop and append. But then in the second part I had to pop them all at once and then insert them into the list in the reverse order. I discovered deque which has methods appendleft and popleft which I used for the first time.

>>> from collections import deque
>>> l = [1, 2, 3]
>>> l.append(4)
>>> l
[1, 2, 3, 4]
>>> temp = deque()
>>> temp.append(5)
>>> temp
deque([5])
>>> temp.append(6)
>>> temp
deque([5, 6])
>>> temp.appendleft(7)
>>> temp
deque([7, 5, 6])
>>> l.extend(temp)
>>> l
[1, 2, 3, 4, 7, 5, 6]
>>> temp
deque([5, 6])
>>> temp.extendleft([7, 8])
>>> temp
deque([8, 7, 5, 6])

It also has an interesting method rotate:

>>> temp
deque([6, 5, 7, 8])
>>> temp.rotate(2)
>>> temp
deque([7, 8, 6, 5])
Mia Bajić's Picture

About Mia Bajić

I’m a Prague-based software engineer passionate about knowledge sharing & community building. I’m the main organizer of Prague Python Pizza & Prague Python meetups, and a co-organizer of EuroPython & PyCon CZ.