Python – Remove first element of list
Queue data structure is very well known data structure, lists in Python usually appends the elements to the end of the list. For implementing a queue data structure, it is essential to be able to remove the front element from a list.
Let’s discuss the ways of removing first element of the list.
Method #1 : Using pop(0)
This method pops, i.e removes and prints the i’th element from the list. This method is mostly used among the other available options to perform this task. This changes the original list.
# Python3 code to demonstrate # removing front element # using pop(0) # initializing list test_list = [ 1 , 4 , 3 , 6 , 7 ] # Printing original list print ( "Original list is : " + str (test_list)) # using pop(0) to # perform removal test_list.pop( 0 ) # Printing modified list print ( "Modified list is : " + str (test_list)) |
Output :
Original list is : [1, 4, 3, 6, 7] Modified list is : [4, 3, 6, 7]
Method #2 : Using del list[0]
This is just the alternate method to perform the front deletion, this method also performs the removal of list element in place and decreases the size of list by 1.
# Python3 code to demonstrate # removing front element # using del list[0] # initializing list test_list = [ 1 , 4 , 3 , 6 , 7 ] # Printing original list print ( "Original list is : " + str (test_list)) # using del list[0] to # perform removal del test_list[ 0 ] # Printing modified list print ( "Modified list is : " + str (test_list)) |
Output :
Original list is : [1, 4, 3, 6, 7] Modified list is : [4, 3, 6, 7]
Method #3 : Using Slicing
Slicing is another approach by which this problem can be solved, we can slice the list from second element till last and assign to the empty list. This does not do the inplace conversion as in case of above two methods.
# Python3 code to demonstrate # removing front element # using slicing # initializing list test_list = [ 1 , 4 , 3 , 6 , 7 ] # Printing original list print ( "Original list is : " + str (test_list)) # using slicing to # perform removal res = test_list[ 1 :] # Printing modified list print ( "Modified list is : " + str (res)) |
Output :
Original list is : [1, 4, 3, 6, 7] Modified list is : [4, 3, 6, 7]
Method #4 : Using deque() + popleft()
This is lesser known method to achieve this particular task, converting the list into deque and then performing the popleft, removes the element from the front of the list.
# Python3 code to demonstrate # removing front element # using deque() + popleft() from collections import deque # initializing list test_list = [ 1 , 4 , 3 , 6 , 7 ] # Printing original list print ( "Original list is : " + str (test_list)) # using deque() + popleft() to # perform removal res = deque(test_list) res.popleft() # Printing modified list print ( "Modified list is : " + str ( list (res))) |
Output :
Original list is : [1, 4, 3, 6, 7] Modified list is : [4, 3, 6, 7]
Last Updated on August 30, 2021 by admin