Python Deque In Collections Tutorial – Complete Guide

Step into the fascinating world of Python programming as we delve into the concept of DeQue in collections. As game creators and developers, understanding the functionality and practicality of DeQue will enhance your coding efficiency and open up a new route to tackle data processing.

What is DeQue?

A part of the collections module, DeQue, which is short for Double Ended Queue, is an exciting data structure in Python. It’s akin to a ‘deque’ imitating real-life queues but with a twist, as elements can be inserted or removed from both ends.

DeQue has an edge over lists in Python as it brings more flexibility and speed, especially when dealing with larger data sets. Let’s imagine being in a gaming scenario where you have an inventory of weapons to navigate. You can add, remove or fetch weapons from anywhere in this ‘queue’ using DeQue, making it a preferred choice for an immersive and responsive gaming experience.

With its speedy and adaptable capabilities, mastering DeQue improves your data handling proficiency. For developers and coders, understanding DeQue does not only boost your Python knowledge but is also a practical skill that can be used in various applications, including game development and artificial intelligence.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

How to Use DeQue – A Basic Example

Let’s begin our journey in understanding DeQue with a simple example. Firstly, to use deque in Python, you need to import it from the collections module:

import collections

# creating deque
de = collections.deque([1,2,3])

print(de)

Running this code will output: deque([1, 2, 3]). We’ve successfully created a deque with elements 1, 2 and 3.

Adding Elements in DeQue

Now, let’s look at how to add elements in DeQue using the append() and appendleft() functions:

import collections

de = collections.deque([1,2,3])

# adding elements to the right
de.append(4)
print('Deque after adding element at end : ',de)

# adding elements to the left 
de.appendleft(0)
print('Deque after adding element at start : ',de)

The append() function adds a value at the right end whereas appendleft() adds a value at the left end. In our example, ‘4’ is added to the end of our deque and ‘0’ is added to the start.

Removing Elements in DeQue

Similarly, you can remove elements from both ends of the DeQue using pop() and popleft() functions:

import collections

de = collections.deque([1,2,3,4])

# removing element from the end
de.pop()
print('Deque after deleting element from end : ',de)

# removing element from the start
de.popleft()
print('Deque after deleting element from start : ',de)

The pop() function removes and returns an element from the right side of the deque whereas popleft() removes an element from the left side.

Using DeQue in Extended Applications

Here we’ll discuss how deque can be used for more extended applications such as rotating items or even reversing the whole deque:

import collections

de = collections.deque([1,2,3,4,5])

# rotating the deque
de.rotate(-1) 
print('Deque after left rotation : ',de)

# reversing the deque
de.reverse()     
print('Deque after reversing : ',de)

The rotate function rotates the deque by the number given as an argument. A positive number rotates to the right, a negative to the left. The reverse function, as the name suggests, reverses the elements of deque.

And voila! You’ve mastered the basics of DeQue in Python. Armed with this new Python instrument, you’re one step closer to becoming a more proficient game developer or coder!

Clearing the DeQue

We might encounter scenarios where we need to empty or clear the existing DeQue. Python makes this operation straightforward with the clear() function:

import collections

de = collections.deque([1,2,3,4,5])

# clearing the deque
de.clear()
print('Deque after clearing : ',de)

The clear() function will clear all elements in the DeQue, leaving us with an empty DeQue as shown by the output: deque([]).

Inserting Elements at a Specific Position

Unlike lists, adjusting elements at specific positions in a DeQue is not inherently supported. But fear not, Python’s insert() method allows us to do just that:

import collections

de = collections.deque([1,2,3,4,5])

# inserting elements at a specific position
de.insert(2, 'new')
print('Deque after inserting element at specific position : ',de)

Here, the insert() function is used to insert the string “new” at the second position of the DeQue.

Deleting Elements at a Specific Position

Continuing on, let’s peek at how to remove elements at a specific position. The pop() function is our friend this time:

import collections

de = collections.deque([1,2,3,4,5])

# deleting elements at specific position
del de[2]
print('Deque after deleting element at specific position : ',de)

The del function helps us to delete the element at the second position of the DeQue as seen in the output.

Counting the Occurrences of Elements

It can often be necessary to count the number of occurrences of a certain element in the DeQue. Python allows us to do that easily with the count() function:

import collections

de = collections.deque([1,2,1,1,2,3,4,2,5])

# counting occurrences of an element
count = de.count(2)
print('Number of occurrences of 2 : ',count)

The count function counts the number of occurrences of the element ‘2’ in our DeQue.

Operating on DeQue in Thread-Safe Manner

Python’s DeQue is built to be thread-safe and can be used in a multi-threaded environment. Check out how elements can be added or removed in a thread-safe manner:

import collections
from threading import Thread

de = collections.deque([1,2,3,4,5])

def thread_function():
    de.append(6)
    print('Deque after append in thread: ', de)

# created Thread
t = Thread(target=thread_function) 

# starting thread
t.start()

# wait until thread finishes its job
t.join()

In this example, we safely appended ‘6’ to DeQue in a new thread. This is one of the ways we provide concurrency handling in Python.

Where to Go Next?

Mountain climber Sir Edmund Hillary famously said, “It is not the mountain we conquer, but ourselves”. Becoming a coding maestro is similar to scaling a mountain. Each line of code is a step and the journey is one of self-discovery and growth. Now that you have scaled the height of DeQue in Python, your exploratory trek awaits. Where to next?

We at Zenva would like to extend an invitation to join our Python Mini-Degree program. This comprehensive bundle of courses covers everything from coding basics and algorithms to object-oriented programming, game development, and app development. Python is a versatile language, renowned for its simplicity and supported by a vast array of libraries. Learning Python opens doors to various industries including data science, machine learning, space exploration, and robotics.

Our courses are designed with the needs of both beginners and more experienced programmers in mind. The approach is hands-on, with step-by-step projects that allow you to create and experiment as you learn, building a portfolio of Python projects in the process. Our courses are delivered online, giving you the flexibility to learn at your own pace, and are taught by experienced instructors who are esteemed in their respective fields.

Embarking on our Python Mini-Degree adventure is an investment in your future. Arm yourself with skills that are highly sought after in the job market and continue on your journey to become a true Pythonosaur.

If you want to explore more specific subjects or broaden your Python knowledge, we invite you to check out our wide range of Python courses. Each of these courses aims to empower you with the right tools and knowledge to make your mark in the coding world.

Conclusion

Acquiring Python skills such as understanding DeQue doesn’t just make you a better coder—it opens up a world of opportunities. Whether you’re working on a passion project, aiming to secure a promising job, or simply ensuring that your skills remain cutting-edge and relevant, Python programming is an essential tool in your coding toolkit.

The digital world is your sandbox, and Python is one of the most powerful tools you can use to mold it to your liking. To put it into perspective, every line of code you write is a brick in your ever-evolving castle. Get ready to level up and create something extraordinary with us at Zenva.

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.