+

Python | Add at the front and remove at the back

Method # 1: Using the + operator and slicing the list
These operators can be used to accomplish this particular task. The add operation can be done using the + operator, and the back removal can be done using a regular slice of the list.

# Python3 demo code
# add in front and remove in back
# use the + operator and slice the list

 
# initializing list

test_list = [ 4 , 5 , 7 , 3 , 10 ]

  
# print original list

print ( "The original list:" + str (test_list))

 
# use the + operator and slice the list
# add in front and remove in the back

res = [ 13 ] + test_list [: - 1 ]

 
# print result

print ( "The list after append and removal:" + str (res))

Output:

 The original list: [4, 5, 7, 3, 10] The list after append and removal: [13, 4, 5, 7, 3] 

Method # 2: Using collections.deque()
A double ended queue can be used to do this particular task, which supports python using the collection library to get the job done the appendleft and pop methods of the queue function can be used.

# Python3 demo code
# add at the front and remove at the back
# use collection.deque

from collections import deque

 
# initializing list

test_list = [ 4 , 5 , 7 , 3 , 10 ]

 
# print the original list

print ( "The original list:" + str (test_list))

 < / code> 
# using collection.deque
# add in front and remove in back

res = deque (test_list)

res.appendleft ( 13 )

res.pop ()

res = list (res)

 
# print result

print ( "The list after append and removal:" + str (res))

Output:

 The original list: [4, 5, 7, 3, 10] The list aft er append and removal: [13, 4, 5, 7, 3] 
Get Solution for free from DataCamp guru