-4

How to compare string in list

a = [['abc','Hello World'],['bcd','Hello Python']]
b = [['abc','Hello World'],['bcd','Hello World'],['abc','Python World']]

I want to compare every value between two lists. For one, I want result to be (values in b but not in a):

[['bcd','Hello World'],['abc','Python World']]

Other one to be (values in a but not in b):

['bcd','Hello Python']

2 Answers2

1

This is a job for sets

Convert your lists of lists to sets of tuples (you can't have sets of lists, as sets can only contain hashable objects, which lists, as all built-in mutable objects, are not)

a = set(map(tuple, [['abc','Hello World'],['bcd','Hello Python']]))
b = set(map(tuple, [['abc','Hello World'],['bcd','Hello World'],['abc','Python World']]))

or create them directly as sets of tuples:

a = {('abc','Hello World'),('bcd','Hello Python')}
b = {('abc','Hello World'),('bcd','Hello World'),('abc','Python World')}

You can then easily and efficiently get your differences:

print(b - a)
# {('abc', 'Python World'), ('bcd', 'Hello World')}

print(a - b)
# {('bcd', 'Hello Python')}

or even the intersection

print(a & b)
# {('abc', 'Hello World')}

or the union:

print(a | b)
# {('abc', 'Python World'), ('bcd', 'Hello World'), ('abc', 'Hello World'), ('bcd', 'Hello Python')}
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
0

If you want to have a quick solution without much concerns about performance you can use

b_not_in_a = [i for i in b if i not in a]
a_not_in_b = [i for i in a if i not in b]
Nick
  • 137
  • 3
  • 13