Let's say that I have lists list_1=['a','b','c','d','e','f'] and list_2=['a','b','c','d']. I would like to know a method so that I can check automatically which strings are absent in list_2 but present in list_1. This is to be done on much longer lists.
Asked
Active
Viewed 48 times
-3
4 Answers
1
You can use set.difference for the task:
list_1=['a','b','c','d','e','f']
list_2=['a','b','c','d']
print( set(list_1).difference(list_2) )
Prints:
{'e', 'f'}
Andrej Kesely
- 118,151
- 13
- 38
- 75
1
answer = set(list_1) - set(list_2)
This should work for you
Vishal Singh
- 5,673
- 2
- 16
- 30
InfoLearner
- 14,232
- 18
- 69
- 117
0
Once more method to get your desired output:
d=['a','b','c','d','e','f']
e=['a','b','c','d']
f=[]
for i in d:
if (i not in e):
f.append(i)
print(f)
Addy
- 384
- 3
- 13
0
You could create your resulting set using a set comprehension:
result = {item for item in list_1 if item not in list_2}
print(result)
{'e', 'f'}