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:
Python | Remove given element from the list
Next article icon

Python | Remove element from given list containing specific digits

Last Updated : 05 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a list, the task is to remove all those elements from list which contains the specific digits. 

Examples: 

Input: lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16]        no_delete = ['2', '3', '4', '0'] Output: [1, 5, 6, 7, 8, 9, 11, 15, 16] Explanation: Numbers 2, 3, 4, 10, 12, 13, 14 contains digits  from no_delete, therefore remove them.  Input: lst = [1, 2, 3, 4, 5, 6, 7, 8, 13, 15, 16]        no_delete = {'6', '5', '4', '3'} Output: [1, 2, 7, 8, 9, 10, 11, 12] Explanation: Numbers 3, 4, 5, 6, 13, 14, 15, 16 contains digits  from no_delete, therefore remove them.

  Below are some methods to do the task. 

Method #1: Using Iteration 

Python3

# Python code to remove all those elements
# from list which contains certain digits
 
# Input List Initialisation
Input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16]
 
# Numbers to delete
no_delete = [1, 0]
 
# Output List Initialisation
Output = []
 
# Using iteration to remove all the elements
for elem in Input:
    flag = 1
    temp = elem
    while elem > 0:
        rem = elem % 10
        elem = elem//10
        if rem in no_delete:
            flag = 0
    if flag == 1:
        Output.append(temp)
 
# Printing Output
print("Initial list is :", Input)
print("Delete list :", no_delete)
print("List after removing elements is :", Output)
                      
                       
Output:
Initial list is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16] Delete list : [1, 0] List after removing elements is : [2, 3, 4, 5, 6, 7, 8, 9]

  Method #2: Using List comprehension and any() function 

Python3

# Python code to remove all those elements from list
# which contains certain digits
 
# Input List Initialisation
Input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16]
 
# Numbers to delete
no_delete = ['2', '3', '4', '0']
 
# using list comprehension and any()
Output = [a for a in Input if not
          any(b in no_delete for b in str(a))]
 
# Printing Output
print("Initial list is :", Input)
print("Delete list :", no_delete)
print("List after removing elements is :", Output)
                      
                       
Output:
Initial list is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16] Delete list : ['2', '3', '4', '0'] List after removing elements is : [1, 5, 6, 7, 8, 9, 11, 15, 16]

  Method #3: Using List comprehension and set() 

Python3

# Python code to remove all those elements from list
# which contains certain digits
 
# Input List Initialisation
Input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16]
 
# Numbers to delete
no_delete = {'6', '5', '4', '3'}
 
# Using list comprehension and set
Output = [x for x in Input
         if not no_delete & set(str(x))]
 
# Printing Output
print("Initial list is :", Input)
print("Delete list :", no_delete)
print("List after removing elements is :", Output)
                      
                       
Output:
Initial list is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16] Delete list : {'3', '4', '6', '5'} List after removing elements is : [1, 2, 7, 8, 9, 10, 11, 12]

Time complexity: O(n*n), where n is the length of the test_list. The List comprehension and set() takes O(n*n) time
Auxiliary Space: O(n), where n is the number of elements in the input list

Method #4: Using the filter function to remove elements

This method uses a lambda function and the all function to check if all digits in the element are not present in the set of digits to delete. The filtered list is then obtained using the filter function.

Here is an example of using the filter function to remove elements containing specific digits from a list:

Python3

# Define a set of digits to delete
no_delete = {'2', '3', '4', '0'}
 
# Initialize input list
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16]
 
# Filter out elements containing digits from the set of digits to delete
filtered_lst = list(filter(lambda x: all(digit not in no_delete for digit in str(x)), lst))
 
# Print the input and output lists
print("Initial list is :", lst)
print("Delete list :", no_delete)
print("List after removing elements is :", filtered_lst)
#This code is contributed by Edula Vinay Kumar Reddy
                      
                       

Output
Initial list is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16] Delete list : {'0', '4', '2', '3'} List after removing elements is : [1, 5, 6, 7, 8, 9, 11, 15, 16]

The time complexity of the filter approach is O(n*m), where n is the length of the input list.  m is number of no delete list.

The space complexity of the filter approach is also O(n), as the filtered list must be stored in memory. This is because the filter function returns a new list containing only the elements that meet the specified condition.

Method #5: Using operator.countOf() method

Python3

import operator as op
# Define a set of digits to delete
no_delete = {'2', '3', '4', '0'}
 
# Initialize input list
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16]
 
# Filter out elements containing digits from the set of digits to delete
filtered_lst = list(filter(lambda x: all(op.countOf(
    no_delete, digit) == 0 for digit in str(x)), lst))
 
# Print the input and output lists
print("Initial list is :", lst)
print("Delete list :", no_delete)
print("List after removing elements is :", filtered_lst)
# This code is contributed by vikkycirus
                      
                       

Output
Initial list is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16] Delete list : {'3', '4', '0', '2'} List after removing elements is : [1, 5, 6, 7, 8, 9, 11, 15, 16]

Time Complexity:O(N)

Auxiliary Space: O(N)

Method#6: Using regular expressions

Python3

import re
 
# Input List Initialisation
Input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16]
 
# Numbers to delete
no_delete = ['2', '3', '4', '0']
 
def check_delete(num):
    pattern = '|'.join(no_delete)
    return not bool(re.search(pattern, str(num)))
 
Output = list(filter(check_delete, Input))
 
# Printing Output
print("Initial list is :", Input)
print("Delete list :", no_delete)
print("List after removing elements is :", Output)
#This code contributed Vinay Pinjala.
                      
                       

Output
Initial list is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16] Delete list : ['2', '3', '4', '0'] List after removing elements is : [1, 5, 6, 7, 8, 9, 11, 15, 16]

Time Complexity:O(N)

Auxiliary Space: O(N)

Method#7: Using Recursive method.

Algorithm:

  1. Define a function remove_digits that takes two arguments, input_list and no_delete.
  2. If the input_list is empty, return an empty list.
  3. Check if the first element of the input_list contains any digits to delete using a while loop and a flag variable.
  4. If the flag is still set to 1, it means the first element can be kept in the output list, so append it to the result of calling remove_digits recursively with the rest of the input_list.
  5. If the flag is set to 0, skip the first element and call remove_digits recursively with the rest of the input_list.
  6. Return the final output list.
  7. Call the remove_digits function with an example input and print the output.
     

Python3

def remove_digits(input_list, no_delete):
    # base case: empty input list
    if not input_list:
        return []
     
    # recursive case: remove the first element if it doesn't contain any digits to delete
    elem = input_list[0]
    flag = 1
    temp = elem
    while elem > 0:
        rem = elem % 10
        elem = elem // 10
        if rem in no_delete:
            flag = 0
    if flag == 1:
        return [temp] + remove_digits(input_list[1:], no_delete)
    else:
        return remove_digits(input_list[1:], no_delete)
     
# Input List Initialisation
Input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16]
# Numbers to delete
no_delete = [1, 0]
Output = remove_digits(Input, no_delete)
# Printing Output
print("Initial list is:", Input)
print("Digits to delete are:", no_delete)
print("List after removing elements is:", Output)
#This code contributed by tvsk.
                      
                       

Output
Initial list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16] Digits to delete are: [1, 0] List after removing elements is: [2, 3, 4, 5, 6, 7, 8, 9]

The time complexity of this solution is O(nm), where n is the length of the input list and m is the maximum number of digits in an element of the input list. This is because we iterate over each element of the input list and each digit in each element. 

The space complexity is also O(n), since we store the output list and call the remove_digits function recursively for each element of the input list.

Approch using Numpy:

In this approach, we first convert the input list into a NumPy array. We then use a NumPy function called logical_not to obtain the logical NOT of the boolean array generated by the list comprehension that checks if any of the elements in the input list contain the specified digits. We use the set function to convert the element to a set of characters and check if there is any overlap between the set and the no_delete set using the & operator. Finally, we index the input array using the logical NOT of the boolean array to obtain the output.

Python3

import numpy as np
 
# Input List Initialization
Input = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16])
 
# Numbers to delete
no_delete = {'2', '0', '4', '3'}
 
# Using NumPy to remove all the elements
Output = Input[np.logical_not(
    [bool(set(str(elem)) & no_delete) for elem in Input])]
 
# Printing Output
print("Initial list is :", Input)
print("Delete list :", no_delete)
print("List after removing elements is :", Output)
                      
                       

Output:

Initial list is : [ 1  2  3  4  5  6  7  8  9 10 11 12 14 13 15 16] Delete list : {'3', '0', '2', '4'} List after removing elements is : [ 1  5  6  7  8  9 11 15 16]

Time Complexity:
The time complexity of this approach is O(n), where n is the length of the input list. This is because we iterate through the input list only once.

Space Complexity:
The space complexity of this approach is O(n), where n is the length of the input list. This is because we create a NumPy array of size n and a boolean array of size n to store the output.



Next Article
Python | Remove given element from the list
author
everythingispossible
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python | Remove given element from the list
    Given a list, write a Python program to remove the given element (list may have duplicates) from the given list. There are multiple ways we can do this task in Python. Let's see some of the Pythonic ways to do this task. Example: Input: [1, 8, 4, 9, 2] Output: [1, 8, 4, 2] Explanation: The Element 9
    7 min read
  • Python | Remove List elements containing given String character
    Sometimes, while working with Python lists, we can have problem in which we need to perform the task of removing all the elements of list which contain at least one character of String. This can have application in day-day programming. Lets discuss certain ways in which this task can be performed. M
    7 min read
  • Python Program to remove a specific digit from every element of the list
    Given a list of elements, the task here is to write a Python program that can remove the presence of all a specific digit from every element and then return the resultant list. Examples: Input : test_list = [333, 893, 1948, 34, 2346], K = 3 Output : ['', 89, 1948, 4, 246] Explanation : All occurrenc
    7 min read
  • Remove Elements From a List Based on Condition in Python
    In Python, lists are a versatile and widely used data structure. There are often situations where you need to remove elements from a list based on a specific condition. In this article, we will explore five simple and commonly used methods to achieve this task. Remove Elements From A List Based On A
    3 min read
  • Remove an Element from a List by Index in Python
    We are given a list and an index value. We have to remove an element from a list that is present at that index value in a list in Python. In this article, we will see how we can remove an element from a list by using the index value in Python. Example: Input: [1, 2, 3, 4, 5], index = 2 Output: [1, 2
    3 min read
  • Python | Remove trailing empty elements from given list
    When working with lists in Python, it's common to encounter lists with extra None elements at the end. These trailing None values can cause issues in our programs . We can remove these trailing None elements using simple methods like slicing, loops, or filter. Using List Slicing Slicing is a very ef
    3 min read
  • Python | Remove given element from list of lists
    The deletion of elementary elements from list has been dealt with many times, but sometimes rather than having just a one list, we have list of list where we need to perform this particular task. Having shorthands to perform this particular task can help. Let's discuss certain ways to perform this p
    6 min read
  • Python | Remove given character from Strings list
    Sometimes, while working with Python list, we can have a problem in which we need to remove a particular character from each string from list. This kind of application can come in many domains. Let's discuss certain ways to solve this problem. Method #1 : Using replace() + enumerate() + loop This is
    8 min read
  • How to get specific elements from list in python
    In this article, we will learn how to get specific item(s) from given list. There are multiple methods to achieve this. Most simple method is accessing list item by Index. [GFGTABS] Python a = [1, 'geeks', 3, 'for', 5] # accessing specific list item with their indices item1 = a[1] it
    3 min read
  • Python - List Elements with given digit
    Given list of elements and a digit K, extract all the numbers which contain K digit. Input : test_list = [56, 72, 875, 9, 173], K = 5 Output : [56, 875] Explanation : 56 and 875 has "5" as digit, hence extracted. Input : test_list = [56, 72, 875, 9, 173], K = 4 Output : [] Explanation : No number ha
    6 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