For example, I have two lists
A = [6, 7, 8, 9, 10, 11, 12] subset_of_A = [6, 9, 12]; # the subset of A the result should be [7, 8, 10, 11]; the remaining elements
Is there a built-in function in python to do this?
JavaScript Array filter() The filter() method creates a new array filled with elements that pass a test provided by a function. The filter() method does not execute the function for empty elements. The filter() method does not change the original array.
Python's filter() is a built-in function that allows you to process an iterable and extract those items that satisfy a given condition. This process is commonly known as a filtering operation.
To filter a list in Python, use the built-in filter() function.
If the order is not important, you should use set.difference
. However, if you want to retain order, a simple list comprehension is all it takes.
result = [a for a in A if a not in subset_of_A]
EDIT: As delnan says, performance will be substantially improved if subset_of_A
is an actual set
, since checking for membership in a set
is O(1) as compared to O(n) for a list.
A = [6, 7, 8, 9, 10, 11, 12] subset_of_A = set([6, 9, 12]) # the subset of A result = [a for a in A if a not in subset_of_A]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With