1

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?

MaLiN2223
  • 1,290
  • 3
  • 19
  • 40
user5740843
  • 1,540
  • 5
  • 22
  • 42

3 Answers3

0

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!

epattaro
  • 2,330
  • 1
  • 16
  • 29
0

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'}

All is documented here: Python3 Python2

MaLiN2223
  • 1,290
  • 3
  • 19
  • 40
0

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

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105