Q:

Python | Remove all occurrences a given element from the list

belongs to collection: Python List Programs

0

Given a list, and we have to remove all occurrences of a given element from the list in Python.

Example:

    Input:
    list = [10, 20, 10, 30, 10, 40, 10, 50]
    n = 10

    Output:
    list after removing 10 from the list
    list = [20, 30, 40, 50]

Logic:

  • Run a while loop from 0th element to last element's index.
  • Check the element whether it is equal to the number (which is to be removed) or not.
  • If any element of the list is equal to the number (which is to be removed), remove that element from the list.
  • To remove the number from the list, use list.remove() method.
  • After removing the number/element from the list, decrease the length, because one item is deleted, and then continue the loop to check the next item at same index (because after removing the element – next elements shifts to the previous index.
  • If element is not found (i.e. is not removed), then increase the loop counter to check next element.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Example:

# list with integer elements
list = [10, 20, 10, 30, 10, 40, 10, 50]
# number (n) to be removed
n = 10

# print original list 
print ("Original list:")
print (list)

# loop to traverse each element in list
# and, remove elements 
# which are equals to n
i=0 #loop counter
length = len(list)  #list length 
while(i<length):
	if(list[i]==n):
		list.remove (list[i])
		# as an element is removed	
		# so decrease the length by 1	
		length = length -1  
		# run loop again to check element							
		# at same index, when item removed 
		# next item will shift to the left 
		continue
	i = i+1

# print list after removing given element
print ("list after removing elements:")
print (list)

Output

    Original list:
    [10, 20, 10, 30, 10, 40, 10, 50]
    list after removing elements:
    [20, 30, 40, 50]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python List Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Program to remove all elements in a range... >>
<< Python | Program to remove first occurrence of a g...