Python | Remove this item from the list

Python Methods and Functions

Method # 1: Using the pop () method [Remove the given element found first.]

# Python program to remove this item from the list

list1 = [ 1 , 9 , 8 , 4 , 9 , 2 , 9

 
# Print starting list

print ( "original list:" + str ( list1)) 

 

remove = 9

 
# using pop ()
# remove list item 9

if remove in list1: 

list1.pop (list1.index (remove)) 

  
# Print list after deletion

print ( "List after element removal is:"   + str < / code> (list1)) 

Exit :

 original list: [1, 9, 8, 4, 9, 2, 9] List after element removal is: [1, 8, 4, 9, 2, 9] 

Method # 2: Using the remove()

method

# Python program to remove this element from the list

list1 = [ 1 , 9 , 8 , 4 , 9 , 2 , 9

  
# Print start list

print ( "original list:" + str (list1)) 

 
# using remove () to remove a list item 9

list1.remove ( 9

 

 
# Print the list after deletion

print ( " List after element removal is: "  + str (list1)) 

Output:

 original list: [1, 9, 8, 4, 9, 2, 9] List after element removal is: [1, 8, 4, 9, 2, 9] 

Now let's see how to remove all occurrences of this element.

Method # 3: Using a set

Since the list is converted to a set, all duplicates are removed, but the order of the list cannot be preserved.

# Python program to remove this item from the list

list1 = [ 1 , 9 , 8 , 4 , 9 , 2 , 9

 
# Print the initial list

print ( "original list: " + str (list1)) 

 
# using discard () method to remove list item 9

list1 = set (list1 ) 

list1.discard ( 9

 

list1 = list (list1) 

  

  
# Print list after deletion

print ( "List after element removal is:"   + str (list1)) 

Exit:

 original list: [1, 9, 8, 4, 9, 2, 9] List after element removal is: [8, 1, 2, 4] 

Method # 4: Using the comprehension list

# Python program to remove this element from the list

list1 = [ 1 , 9 , 8 , 4 , 9 , 2 , 9

 
# Print the initial list

print ( "original list: " + str (list1)) 

 
# using comprehension list
# remove list item 9

list1 = [ ele for ele in list1 if ele! = 9

 
# Print list after deletion

print ( "List after element removal is: "  + str (list1)) 

Exit:

 original list: [1, 9, 8, 4, 9, 2, 9] List after element removal is: [1, 8, 4, 2] 




Get Solution for free from DataCamp guru