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?
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?
>>> 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]
If they are both sets you can do this:
set(rt) - set(dp)
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)
You are probably looking for one of these:
>>> rt = [1,2,3]
>>> dp = [1,2]
>>> set(rt).issubset(dp)
False
>>> 3 in dp
False
Sounds like you may want set subtraction:
>>> rt = [1,2,3]
>>> dp = [1,2]
>>> set(rt) - set(dp)
set([3])
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!')