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
  • 75,446
  • 119
  • 278
  • 425

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
  • 43,129
  • 11
  • 115
  • 108
3

If they are both sets you can do this:

set(rt) - set(dp)
jamylak
  • 128,818
  • 30
  • 231
  • 230
matcauthon
  • 2,261
  • 1
  • 24
  • 41
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
  • 110,290
  • 27
  • 149
  • 241
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
  • 128,818
  • 30
  • 231
  • 230
1

Sounds like you may want set subtraction:

>>> rt = [1,2,3]
>>> dp = [1,2]
>>> set(rt) - set(dp)
set([3])
Jeff Bradberry
  • 1,597
  • 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
  • 553
  • 2
  • 6
  • 15