Home » Python programs

Python | Remove all occurrences a given element from the list

Here, we are going to implement a Python program that will remove all occurrences a given element from the list.
Submitted by IncludeHelp, on August 06, 2018

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.

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]





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.