Introduction
In Python, the collections.deque is a powerful data structure that allows fast appending and popping from both ends. It’s part of the collections
module and offers a more efficient alternative to lists when it comes to operations that involve frequent insertions or deletions from the ends of the collection.
Objective
This guide aims to help you understand how to use collections.deque
for handling data efficiently. By the end of this tutorial, you should be able to use deque
for applications like queue management, sliding window problems, and more.
Code Example
from collections import deque # Create an empty deque dq = deque() # Add elements to the right side of the deque dq.append(10) dq.append(20) dq.append(30) print("Deque after append:", dq) # Add elements to the left side of the deque dq.appendleft(5) dq.appendleft(1) print("Deque after appendleft:", dq) # Pop elements from the right side right_pop = dq.pop() print("Popped from right:", right_pop) # Pop elements from the left side left_pop = dq.popleft() print("Popped from left:", left_pop) # Rotate the deque dq.rotate(2) print("Deque after rotating by 2:", dq) # Access the deque print("First element:", dq[0]) print("Last element:", dq[-1])
Program Explanation
In this Python program, we:
- Import the deque class from the collections module.
- Initialize an empty deque and add elements to both ends using
append
andappendleft
methods. - Use the
pop
andpopleft
methods to remove elements from the right and left ends, respectively. - Demonstrate the use of
rotate
to shift all elements of the deque by a specified number of positions. - Access elements using indexing (
[0]
for the first and[-1]
for the last element).
How to Run the Program
To run this program:
- Ensure you have Python installed on your system (Python 3.x recommended).
- Copy the provided code into a Python script (e.g.,
deque_example.py
). - Open a terminal or command prompt and navigate to the directory containing the script.
- Run the script by typing
python deque_example.py
in your terminal.
The output will be printed on the console, showing the manipulation of the deque with various operations.