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:

  • Traverse each number in the list by using for...in loop.
  • 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.

Example:

# list with integer elements
list = [10, 20, 10, 30, 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
for i in list:
	if(i==n):
		list.remove (i)

# print list after removing ODD elements 
print "list after removing ODD elements:"
print list

Output

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



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.