Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array filter in python?

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?

like image 249
kn3l Avatar asked Apr 12 '11 19:04

kn3l


People also ask

What is array filter ()?

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.

What is filter () in Python?

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.

How do you filter a list in Python?

To filter a list in Python, use the built-in filter() function.


1 Answers

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] 
like image 104
Chinmay Kanchi Avatar answered Oct 20 '22 06:10

Chinmay Kanchi