I currently have two lists:
str1 = ['test1.jpg', 'test2.jpg', 'test3.jpg']
str2 = ['test1.jpg', 'test2.jpg']
As you may well notice, test3.jpg is missing from str2. Is there a way I can compare str2 with str1 and find the missing pieces?
I currently have two lists:
str1 = ['test1.jpg', 'test2.jpg', 'test3.jpg']
str2 = ['test1.jpg', 'test2.jpg']
As you may well notice, test3.jpg is missing from str2. Is there a way I can compare str2 with str1 and find the missing pieces?
well. those are actually 2 list of strings you got there.
One simple way to compare 'em would be to:
missing = [x for x in str1 if x not in str2]
missing
Out:
['test3.jpg']
hope that helps!
You can use built-in type set
str1 = ['test1.jpg', 'test2.jpg', 'test3.jpg']
str2 = ['test1.jpg', 'test2.jpg']
s1 = set(str1)
s2 = set(str2)
print(s1-s2)
From there you can easily create function:
def difference(list1,list2):
return set(list1)-set(list2)
If you want to create difference between both of them you can do the following: For data :
str1 = ['test1.jpg', 'test2.jpg', 'test3.jpg']
str2 = ['test1.jpg', 'test2.jpg', 'test4.jpg']
Funcion would be:
def difference(list1,list2):
return (set(list1)-set(list2)) | (set(list2)-set(list1))
Or :
def difference(list1,list2):
return set(list1).symmetric_difference(set(list2))
Outputs:
{'test3.jpg', 'test4.jpg'}
The solution using Set difference operator:
str1 = ['test1.jpg', 'test2.jpg', 'test3.jpg']
str2 = ['test1.jpg', 'test2.jpg']
diff = list(set(str1) - set(str2))
# the same can be achieved with set.difference(*others) method:
# diff = list(set(str1).difference(set(str2)))
print(diff)
The output:
['test3.jpg']
https://docs.python.org/3/library/stdtypes.html?highlight=set#set.difference