Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Append at front and remove from rear in Python
When working with Python lists, we often need to add elements to the front and remove elements from the rear. Python provides several efficient methods to accomplish this task, both from the standard library and through built-in operators.
Using + Operator with List Slicing
The simplest approach combines list concatenation with slicing to add an element at the front while removing the last element ?
days = ['Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
print("Original list:", days)
# Add 'Mon' at front and remove last element
result = ['Mon'] + days[:-1]
print("After append front and remove rear:", result)
Original list: ['Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] After append front and remove rear: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
Using deque from collections
The deque (double-ended queue) provides efficient operations for adding and removing elements from both ends. This is the preferred method for frequent front/rear operations ?
import collections
days = collections.deque(['Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'])
print('Original deque:', days)
# Add element at front and remove from rear
days.appendleft('Mon')
days.pop()
print('After appendleft and pop:', days)
Original deque: deque(['Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']) After appendleft and pop: deque(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'])
Using insert() and pop() Methods
You can also use list methods directly, though this is less efficient for large lists ?
days = ['Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
print("Original list:", days)
# Insert at front (index 0) and remove from rear
days.insert(0, 'Mon')
days.pop()
print("After insert and pop:", days)
Original list: ['Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] After insert and pop: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
Performance Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| + operator with slicing | O(n) | One-time operations |
| deque operations | O(1) | Frequent front/rear operations |
| insert(0) and pop() | O(n) | Simple list modifications |
Conclusion
Use deque for frequent front/rear operations as it provides O(1) performance. For occasional operations, list slicing with the + operator offers a simple and readable solution.
