1

Possible Duplicate:
Get difference from 2 lists. Python

I have two lists

rt = [1,2,3]
dp = [1,2]

What is the most pythonic way to find out that in the rt list that 3 is not a element of the dp list?

Community
  • 1
  • 1
Tampa
  • 69,424
  • 111
  • 266
  • 409

6 Answers6

7
>>> rt = [1,2,3]
>>> dp = [1,2]

You can use sets:

>>> set(rt) - set(dp)
set([3])

Or a list comprehension:

>>> [x for x in rt if x not in dp]
>>> [3]

EDIT: jamylak pointed out you could use a set to improve the efficiency of membership lookup:

>>> dp_set = set(dp)
>>> [x for x in rt if x not in dp_set]
>>> [3]
GWW
  • 41,431
  • 11
  • 106
  • 104
3

If they are both sets you can do this:

set(rt) - set(dp)
jamylak
  • 120,885
  • 29
  • 225
  • 225
matcauthon
  • 2,191
  • 22
  • 40
3

Any of these will work:

set(rt).difference(set(dp))

OR

[i for i in rt if i not in dp]

OR

set(rt) - set(dp)
inspectorG4dget
  • 104,525
  • 25
  • 135
  • 234
2

You are probably looking for one of these:

>>> rt = [1,2,3]
>>> dp = [1,2]
>>> set(rt).issubset(dp)
False
>>> 3 in dp
False
jamylak
  • 120,885
  • 29
  • 225
  • 225
1

Sounds like you may want set subtraction:

>>> rt = [1,2,3]
>>> dp = [1,2]
>>> set(rt) - set(dp)
set([3])
Jeff Bradberry
  • 1,547
  • 1
  • 12
  • 11
0

Kind of ambiguous what you want. You mean you want to check each element of rt against dp?

for num in rt:
    if num in dp:
        print(num, 'is in dp!')
    else:
        print(num, 'is not in dp!')
Dubslow
  • 424
  • 2
  • 5
  • 15