Python | Removing the first item in the list

Python Methods and Functions

Let's discuss how to remove the first list item.

Method # 1: Using pop(0)

This method issues, i.e. removes and prints the i-th element from the list. This method is mainly used among other available options to accomplish this task. This changes the original list.

# Python3 demo code
# remove the front element
# using pop (0)

 
# initializing list

test_list = [ 1 , 4 , 3 , 6 , 7 ]

 
# Print original list

print ( "Original list is:" + str (test_list))

 
# using pop (0) for
# perform removal

test_list.pop ( 0 )

  
# Print the 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 a An alternative method for removing the leading edge, this method also removes the list item in place and reduces the size of the list by 1.

# Python3 demo code
# remove the front element
# using to-do list [0]

 
# initializing list

test_list = [ 1 , 4 , 3 , 6 , 7 ]

  
# Print original list

print ( " Original list is: " + str (test_list) )

 
# using del list [0] for
# perform deletion

del test_list [ 0 ]

 
# Print modified list

print ( "Modified list is:" + str (test_list))

Output:

 Origi nal list is: [1, 4, 3, 6, 7] Modified list is: [4, 3, 6, 7] 

Method # 3: Using slicing

Slice — this is another approach by which this problem can be solved, we can split the list from the second item to the last and assign an empty list. This does not do the in-place conversion as with the above two methods.

# Python3 demo code
# remove the front element
# using slicing

  
# initializing list

test_list = [ 1 , 4 , 3 , 6 , 7 ]

 
# Print original list

print ( " Original list is: " + str (test_list))

  
# using slicing
# delete

res = test_list [ 1 :]

 
# Print the 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 less a well-known technique for this particular task: converting the list to a deque and then doing popleft, removing the item from the front of the list.

# Python3 demo code
# removing the front element
# using deque () + popleft ()

from collections import deque

 
# init list

test_list = [ 1 , 4 , 3 , 6 , 7 ]

 
# Print original list

print ( "Original list is:" + str (test_list))

  
# using deque () + popleft () for
# perform removal

res = deque (test_list)

res.popleft ()

 
# Print modified cn claim

print ( "Modified list is : " + str ( list (res)))

Output:

 Original list is: [1, 4, 3, 6, 7] Modified list is: [4, 3, 6 , 7] 




Get Solution for free from DataCamp guru