python insert element at given index in deque

Python – Insert Element at a given Index in Deque

In this tutorial, we will look at how to insert an element at a specific index in a deque in Python with the help of some examples.

deque in Python

The collections module in Python comes with a deque class that you can use to implement a stack or queue data structure in Python. Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.

In simple terms, you can think of a deque in Python as a list-like data structure but with efficient insertion and removal of items from either end (left and right). This makes them very useful when implementing a stack or queue functionality in Python.

How to insert an element at sa pecific index in a deque in Python?

python insert element at given index in deque

The deque class comes with a number of built-in functions to help perform common operations (like adding and removing elements).

To insert an element at a given index in a deque in Python, use the insert() function. The following is the syntax –

# insert element "x" at index "i" in deque "queue"
queue.insert(i, x)

It inserts the element x at the index i in the deque.

Note that, by default, deques in Python are unbounded. You can make a deque bounded by setting its maxlen. Now, if you try to insert an element in a bounded deque beyond its maxlen, it will raise an IndexError.

Examples

Let’s now look at some examples of using the above syntax –

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Example 1 – Insert an element at a specific index inside the deque

First, let’s create a deque with some elements.

from collections import deque

# create a deque
queue = deque([1, 2, 3])
# print the deque
print(queue)

Output:

deque([1, 2, 3])

Here, we imported the deque class from the collections module and created a deque object, queue with three elements – 1, 2, and 3.

Now, let’s insert an element at a specific index inside the above deque. For example, let’s insert the element 4 at the index 1.

# insert 4 at index 1 in the deque
queue.insert(1, 4)
# print the deque
print(queue)

Output:

deque([1, 4, 2, 3])

Here, we used the insert() function to insert 4 at the index 1 in the deque, queue. You can see that the deque object contains 4 at index 1 now.

Example 2 – Insert an element outside the index range of deque

What happens if you try to insert an element in a Python deque outside its index range?

For an unbounded deque (deque without any specified maxlen), if you insert an element outside its index range, the element will be inserted at the end of the deque.

For a bounded deque (deque with a specified maxlen), if you insert an element beyond its maxlen it will raise an IndexError.

A deque object, by default, is unbounded (since its maxlen is set to None by default).

Let’s now look at some examples.

First, we will create an unbounded deque and try to insert an element beyond its index range.

# create a deque
queue = deque([1, 2, 3])
# insert 4 at index 5 in the deque
queue.insert(5, 4)
# print the deque
print(queue)

Output:

deque([1, 2, 3, 4])

Here, we created an unbounded deque of length 3 with the index of values ranging from 0 to 2. Now, we tried to insert the element 4 at index 5 in this deque. Notice that the index 5 is outside the index range of the deque and thus the element was inserted at the end of the deque.

Now, let’s do the same thing with a bounded deque. We’ll create a deque with three elements and set its maxlen to 3.

# create a bounded deque
queue = deque([1, 2, 3], maxlen=3)
# insert 4 at index 5 in the deque
queue.insert(5, 4)
# print the deque
print(queue)

Output:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Input In [12], in <module>
      2 queue = deque([1, 2, 3], maxlen=3)
      3 # insert 4 at index 5 in the deque
----> 4 queue.insert(5, 4)
      5 # print the deque
      6 print(queue)

IndexError: deque already at its maximum size

You can see that we get an IndexError. This happened because we are trying to insert an element to a bounded deque beyond its maxlen (the maxlen is 3 and there are already 3 elements in the deque).

Had the maxlen been 4 in the above code, we would’ve been able to insert the element.

# create a bounded deque
queue = deque([1, 2, 3], maxlen=4)
# insert 4 at index 5 in the deque
queue.insert(5, 4)
# print the deque
print(queue)

Output:

deque([1, 2, 3, 4], maxlen=4)

Summary

In this tutorial, we looked at how to insert an element at a specific index in a deque object in Python. The following are the key takeaways –

  • Use the deque insert() function to insert an element at a specific index. Pass the insertion index and the element as comma-separated arguments.
  • If you try to insert an element in a bounded deque beyond its maxlen, it will raise an IndexError.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top