121

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?

amindfv
  • 8,438
  • 5
  • 36
  • 58
tree em
  • 20,379
  • 30
  • 92
  • 130

10 Answers10

168

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]
Chinmay Kanchi
  • 62,729
  • 22
  • 87
  • 114
  • 14
    And this can be improved vastly by making `subset_of_A` a real `set`, which gives `O(1)` membership test (instead of `O(n)` as with lists). –  Apr 12 '11 at 19:47
102

Yes, the filter function:

filter(lambda x: x not in subset_of_A, A)
Letharion
  • 4,067
  • 7
  • 31
  • 42
carlpett
  • 12,203
  • 5
  • 48
  • 82
10

set(A)-set(subset_of_A) gives your the intended result set, but it won't retain the original order. The following is order preserving:

[a for a in A if not a in subset_of_A]
Alexander Gessler
  • 45,603
  • 7
  • 82
  • 122
9

No, there is no build in function in python to do this, because simply:

set(A)- set(subset_of_A)

will provide you the answer.

eat
  • 7,440
  • 1
  • 19
  • 27
5

tuple(set([6, 7, 8, 9, 10, 11, 12]).difference([6, 9, 12]))

NPE
  • 486,780
  • 108
  • 951
  • 1,012
4

How about

set(A).difference(subset_of_A)
JoshAdel
  • 66,734
  • 27
  • 141
  • 140
3

This was just asked a couple of days ago (but I cannot find it):

>>> A = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A = set([6, 9, 12])
>>> [i for i in A if i not in subset_of_A]
[7, 8, 10, 11]

It might be better to use sets from the beginning, depending on the context. Then you can use set operations like other answers show.

However, converting lists to sets and back only for these operations is slower than list comprehension.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
2

Use the Set type:

A_set = Set([6,7,8,9,10,11,12])
subset_of_A_set = Set([6,9,12])

result = A_set - subset_of_A_set
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
1
>>> a = set([6, 7, 8, 9, 10, 11, 12])
>>> sub_a = set([6, 9, 12])
>>> a - sub_a
set([8, 10, 11, 7])
Jake
  • 2,515
  • 5
  • 26
  • 41
1
>>> A           = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A  = [6, 9, 12];
>>> set(A) - set(subset_of_A)
set([8, 10, 11, 7])
>>>