Python insert()
The insert() method of Python’s collections.deque inserts an element at a specified index within the deque. Unlike append() or appendleft(), which add elements only to the ends, insert() can add an element at any valid position.
While deques are optimized for fast appends and pops at both ends, using insert() in the middle may affect performance because it shifts elements internally.
Syntax
deque.insert(index, element)
Parameters:
index: The position where the new element will be inserted.element: The item to insert into the deque.
Return value:
None: This method modifies the deque in place.
Example 1: Inserting an Element at a Specific Position
This example demonstrates inserting elements at specific positions within a deque:
from collections import deque# Create a dequefruits = deque(["apple", "banana", "cherry"])print("Original deque:", fruits)# Insert 'orange' at index 1fruits.insert(1, "orange")print("After inserting 'orange' at index 1:", fruits)
The output of this code is:
Original deque: deque(['apple', 'banana', 'cherry'])After inserting 'orange' at index 1: deque(['apple', 'orange', 'banana', 'cherry'])
Example 2: Using Negative Indices and Edge Insertions
This example demonstrates inserting elements at the beginning and end using positive and negative indices:
from collections import dequecolors = deque(["red", "green", "blue"])# Insert at the beginningcolors.insert(0, "purple")# Insert at the end using len(colors)colors.insert(len(colors), "yellow")# Insert before the last item using negative indexcolors.insert(-1, "cyan")print(colors)
The output of this code is:
deque(['purple', 'red', 'green', 'blue', 'cyan', 'yellow'])
Here, the insert() method demonstrates its flexibility that it can insert items anywhere in the deque.
Codebyte Example: How to Use deque.insert() for Dynamic Insertions
In this example, insert() adds elements at various positions in a deque, demonstrating dynamic insertions at the beginning, middle, and end:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours