Python | Append at front and remove from rear

Being familiar with the concept of queue, which follows FIFO rule, i.e first in first out, that suggests a front removal and rear insertion. This has been discussed many times. But sometimes we need to perform the exact opposite of this and we need to perform the append at front and remove element from the rear. Let’s discuss certain ways in which this can be done.

Method #1 : Using + operator and list slicing
These operators can be used to perform this particular task. The append operation can be done with the help of + operator and the removal of rear can be done using the conventional list slicing.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# append from front and remove from rear
# using + operator and list slicing
  
# initializing list
test_list = [4, 5, 7, 3, 10]
  
# printing original list 
print("The original list : " + str(test_list))
  
# using + operator and list slicing
# append from front and remove from rear
res = [13] + test_list[:-1]
  
# printing result
print("The list after append and removal : " + str(res))

chevron_right


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()
The doubly ended queue can be used to perform this particular task in which is supported by python using the collection library, the appendleft and pop methods of queue function can be used to perform this job.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# append from front and remove from rear
# using collections.deque
from collections import deque
  
# initializing list
test_list = [4, 5, 7, 3, 10]
  
# printing original list 
print("The original list : " + str(test_list))
  
# using collections.deque
# append from front and remove from rear
res = deque(test_list)
res.appendleft(13)
res.pop()
res = list(res)
  
# printing result
print("The list after append and removal : " + str(res))

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.