We are given a list we need to append element in front and remove from rear. For example, a = [10, 20, 30] we need to add 5 in front and remove from rear so that resultant output should be [5, 10, 20].
Using insert
Using insert in Python allows us to add an element at the front of a list by specifying index 0. To remove from the rear we use pop method without arguments which removes and returns last element of list.
a = [10, 20, 30]
# Append 5 at the front
a.insert(0, 5)
# Remove the last element
a.pop()
print(a)
Output
[5, 10, 20]
Explanation:
- a.insert(0, 5) inserts the element 5 at the front of the list.
- a.pop() removes the last element (30), resulting in the modified list [5, 10, 20].
Using list slicing
List slicing enables appending at the front by combining [element] + list. Removing from rear can be done using list[:-1] to exclude the last element..
a = [10, 20, 30]
# Append 5 at the front using slicing
a = [5] + a
# Remove the last element using slicing
a = a[:-1]
print(a)
Output
[5, 10, 20]
Explanation:
- Element
5is appended to the front by creating a new list[5]and concatenating it with the original lista. - Last element is removed using slicing (
a[:-1]), which creates a new list excluding the last element ofa.
Using collections.deque
collections.deque is a double-ended queue that allows fast appending and popping from both ends. It provides appendleft() to add an element at front and pop() to remove an element from the rear efficiently.
from collections import deque
a = deque([10, 20, 30])
# Append 5 at the front using `appendleft`
a.appendleft(5)
# Remove the last element using `pop`
a.pop()
print(list(a))
Output
[5, 10, 20]
Explanation:
- a.appendleft(5) adds element 5 to the front of the deque.
- a.pop() removes last element from the deque, resulting in the modified list [5, 10, 20].