-4

Possible Duplicate:
Python, compute list difference

I have two lists For example:

A = [1,3,5,7]
B = [1,2,3,4,5,6,7,8]

Now, A is always a subset of B I want to generate a third list C: which has elements which are present in B but absent in A like

C = [2,4..]

Thanks

Community
  • 1
  • 1
frazman
  • 29,933
  • 66
  • 171
  • 257

4 Answers4

4

List comprehensions are one way to do this:

[x for x in B if x not in A]

If you use Python, I recommend gaining familiarity with list comprehensions. They're a very powerful tool.

(Several people have suggested using set. While this is a very good idea if you only care about whether or not an element is in the set, note that it will not preserve the order of the elements; a list comprehension will.)

Taymon
  • 23,632
  • 9
  • 61
  • 83
4
>>> set(B) - set(A)
set([8, 2, 4, 6])

or

>>> sorted(set(B) - set(A))
[2, 4, 6, 8]
Fred Foo
  • 342,876
  • 71
  • 713
  • 819
3

An easy way to do this is

C = [x for x in B if x not in A]

This will become slow for big lists, so it would be better to use a set for A:

A = set(A)
C = [x for x in B if x not in A]

If you have multiple operations like this, using sets all the time might be the best option. If A and B are sets, you can simply do

C = B - A
Sven Marnach
  • 530,615
  • 113
  • 910
  • 808
1
C = sorted(list(set(B) - set(A)))

That should do it.

Mark Ransom
  • 286,393
  • 40
  • 379
  • 604