deque

Published onesixx on

from collections import deque

# Create a deque with a maximum length of 6
my_deque = deque(maxlen=6)
my_deque


# Add elements to the deque
my_deque.append(1)
my_deque.append(2)
my_deque.append(3)
# Current state of the deque: deque([1, 2, 3], maxlen=6)

# Add more elements, exceeding the maximum length
my_deque.append(4)
my_deque.append(5)
my_deque.append(6)
my_deque.append(7)
# Current state of the deque: deque([3, 4, 5, 6, 7], maxlen=6)

“double-ended queue

from collections import deque

# Create an empty deque
my_deque = deque()

# Add elements to the deque
my_deque.append(1)      # Add to the right end
my_deque.appendleft(2)  # Add to the left end

# Remove elements from the deque
right_element = my_deque.pop()     # Remove and return the rightmost element
left_element  = my_deque.popleft() # Remove and return the leftmost element

print(my_deque)       # Output: deque([])
print(right_element)  # Output: 1
print(left_element)   # Output: 2
Categories: Python Basic

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x