Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Remove Last Element from List in Python
Next article icon

Remove all the occurrences of an element from a list in Python

Last Updated : 08 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

The task is to perform the operation of removing all the occurrences of a given item/element present in a list. 

Example

Input1: 1 1 2 3 4 5 1 2 1   Output1: 2 3 4 5 2   Explanation : The input list is [1, 1, 2, 3, 4, 5, 1, 2] and the item to be removed is 1.                                 After removing the item, the output list is [2, 3, 4, 5, 2]

Remove all Occurrences of an Item from a Python list

Below are the ways by which we can remove all the occurrences of an Element from a List in Python:

  • Using List Comprehension
  • Using filter and __ne__
  • Using remove()
  • Using replace() methods
  • Using enumerate function

Removing Specific Element from List using list comprehension

The list comprehension can be used to perform this task in which we just check for a match and reconstruct the list without the target element. We can create a sublist of those elements in the list that satisfies a certain condition.

Python3




def remove_items(test_list, item):
  
    # using list comprehension to perform the task
    res = [i for i in test_list if i != item]
    return res
  
# driver code
if __name__ == "__main__":
    test_list = [1, 3, 4, 6, 5, 1]
    # the item which is to be removed
    item = 1
    print("The original list is : " + str(test_list))
  
    # calling the function remove_items()
    res = remove_items(test_list, item)
  
    # printing result
    print("The list after performing the remove operation is : " + str(res))
 
 
Output
The original list is : [1, 3, 4, 6, 5, 1]  The list after performing the remove operation is : [3, 4, 6, 5]  

Time complexity: O(n)
Auxiliary Space: O(n)

Remove all the occurrences of an element Using filter() and __ne__

We filter those items of the list which are not equal __ne__ to the item. In this example, we are using filter() and __ne__ to remove all the occurrences of an element from the list.

Python3




# Python 3 code to demonstrate
# the removal of all occurrences of
# a given item using filter() and __ne__
def remove_items(test_list, item):
  
    # using filter() + __ne__ to perform the task
    res = list(filter((item).__ne__, test_list))
    return res
# driver code
if __name__ == "__main__":
    test_list = [1, 3, 4, 6, 5, 1]
    item = 1
    # printing the original list
    print("The original list is : " + str(test_list))
  
    # calling the function remove_items()
    res = remove_items(test_list, item)
  
    # printing result
    print("The list after performing the remove operation is : " + str(res))
 
 
Output
The original list is : [1, 3, 4, 6, 5, 1]  The list after performing the remove operation is : [3, 4, 6, 5]  

Time Complexity: O(n)
Auxiliary Space: O(n)

Removing Occurrences of item from a list Using remove()

In this method, we iterate through each item in the list, and when we find a match for the item to be removed, we will call remove() function on the list. 

Python3




# Python 3 code to demonstrate
def remove_items(test_list, item):
    # remove the item for all its occurrences
    c = test_list.count(item)
    for i in range(c):
        test_list.remove(item)
    return test_list
    
# driver code
if __name__ == "__main__":
    test_list = [1, 3, 4, 6, 5, 1]
    item = 1
    # printing the original list
    print("The original list is :" + str(test_list))
  
    # calling the function remove_items()
    res = remove_items(test_list, item)
  
    # printing result
    print("The list after performing the remove operation is :" + str(res))
 
 
Output
The original list is :[1, 3, 4, 6, 5, 1]  The list after performing the remove operation is :[3, 4, 6, 5]  

Time Complexity: O(n^2), where n is the length of the input list.
Auxiliary Space: O(1)

Remove Occurrences of an specific item Using  replace()

In this example, we are converting the list into the string and then replacing that element string with empty space such that all occurrences of that element is removed.

Python3




#remove all occurrences of element in list
test_list = [1, 3, 4, 6, 5, 1]
ele=1
a=list(map(str,test_list))
b=" ".join(a)
b=b.replace(str(ele),"")
b=b.split()
x=list(map(int,b))
print(x)
 
 
Output
[3, 4, 6, 5]  

Time Complexity: O(n)
Auxiliary Space: O(n)

Remove Occurrences of an element Using enumerate function

In this example, we are making a new list that doesn’t contain any of that particular element’s occurrences inside the list by using enumerate function.

Python3




test_list = [1, 3, 4, 6, 5, 1] 
ele=1 
x=[j for i,j in enumerate(test_list) if j!=ele] 
print(x)
 
 
Output
[3, 4, 6, 5]  

Time Complexity: O(n)
Auxiliary Space: O(n)



Next Article
Remove Last Element from List in Python

P

pranjalgupta705
Improve
Article Tags :
  • Misc
  • Python
  • Python list-programs
  • python-list
Practice Tags :
  • Misc
  • python
  • python-list

Similar Reads

  • Count occurrences of an element in a list in Python
    A common task when working with lists is to count how many times a specific element appears. In Python, we have several ways to count occurrences of an element using both built-in and custom methods. The simplest and most straightforward way to count occurrences of an element in a list is by using t
    3 min read
  • Remove Last Element from List in Python
    Given a list, the task is to remove the last element present in the list. For Example, given a input list [1, 2, 3, 4, 5] then output should be [1, 2, 3, 4]. Different methods to remove last element from a list in python are: Using pop() methodUsing Slicing TechniqueUsing del OperatorUsing Unpacking
    2 min read
  • Remove all values from a list present in another list - Python
    When we work with lists in Python, sometimes we need to remove values from one list that also exists in another list. Set operations are the most efficient method for larger datasets. When working with larger lists, using sets can improve performance. This is because checking if an item exists in a
    3 min read
  • Remove first element from list in Python
    The task of removing the first element from a list in Python involves modifying the original list by either deleting, popping, or slicing the first element. Each method provides a different approach to achieving this. For example, given a list a = [1, 2, 3, 4], removing the first element results in
    2 min read
  • Ways to remove particular List element in Python
    There are times when we need to remove specific elements from a list, whether it’s filtering out unwanted data, deleting items by their value or index or cleaning up lists based on conditions. In this article, we’ll explore different methods to remove elements from a list. Using List ComprehensionLi
    2 min read
  • Remove falsy values from a list in Python
    Removing falsy values from a list filters out unwanted values like None, False, 0 and empty strings, leaving only truthy values. It's useful for data cleaning and validation. Using List ComprehensionList comprehension is a fast and efficient way to remove falsy values from a list . It filters out va
    2 min read
  • Remove empty tuples from a list - Python
    The task of removing empty tuples from a list in Python involves filtering out tuples that contain no elements i.e empty. For example, given a list like [(1, 2), (), (3, 4), (), (5,)], the goal is to remove the empty tuples () and return a new list containing only non-empty tuples: [(1, 2), (3, 4),
    3 min read
  • Python - Print list after removing element at given index
    In this article, we will explore different ways to remove an element from a list at a given index and print the updated list, offering multiple approaches for achieving this. Using pop()pop() method removes the element at a specified index and returns it. [GFGTABS] Python li = [10, 20, 30, 40, 50] i
    2 min read
  • Remove All Duplicates from a Given String in Python
    The task of removing all duplicates from a given string in Python involves retaining only the first occurrence of each character while preserving the original order. Given an input string, the goal is to eliminate repeated characters and return a new string with unique characters. For example, with
    2 min read
  • Index of Non-Zero Elements in Python list
    We are given a list we need to find all indexes of Non-Zero elements. For example, a = [0, 3, 0, 5, 8, 0, 2] we need to return all indexes of non-zero elements so that output should be [1, 3, 4, 6]. Using List ComprehensionList comprehension can be used to find the indices of non-zero elements by it
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences