-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
  • 32,081
  • 75
  • 184
  • 269

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
  • 24,950
  • 9
  • 62
  • 84
4
>>> set(B) - set(A)
set([8, 2, 4, 6])

or

>>> sorted(set(B) - set(A))
[2, 4, 6, 8]
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
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
  • 574,206
  • 118
  • 941
  • 841
1
C = sorted(list(set(B) - set(A)))

That should do it.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622