SoFunction
Updated on 2024-12-10

Python deque module simple use code example

Recently, when doing problems in pythonTip, I came across the deque module, which I didn't know much about before, but now I would like to summarize it here

The deque module is an item in the python standard library collections that provides sequences that can be manipulated at both ends, meaning that you can perform add or delete operations both before and after the sequence.

deque is a data structure provided by python, thread-safe and more powerful than list.

The code is as follows

from collections import deque

user_list = ['admin', 'root']
user = user_list.pop() # Pop the tail element of a list, lists don't provide a way to manipulate the head element.
print(user, user_list) # root ['admin']

"""
deque is thread-safe with GIL guarantees
list is not thread-safe
"""

#   def __init__(self, iterable=(), maxlen=None)
user_deque = deque(['admin', 'root', 'jet'])

# append adds an element to the end of the deque, i.e., inserts an element from the right.
user_deque.append('md')

# Add an element from the header
user_deque.appendleft('fi')

# pop pops an element from the end
pop_item = user_deque.pop()
print(pop_item)

# Pop an element from the header
pop_left_item = user_deque.popleft()

# extent adds a deque to the original deque, merging the deque. Note: it does not return a new deque.
user_deque.extend(deque(('a1', 'a2')))

# Merge the elements of the deque to the left of the original deque.
user_deque.extendleft(deque([123,456]))

# of statistics
count = user_deque.count(123)
print(count)


print(user_deque)

This is the whole content of this article.