Search code examples
pythonlisttupleselement

Delete all tuples from a list, if the first two elements of another tuple matches


i have two tuple lists, and i want to delete all tuples from list1, if the first two elements of a tuple from list2 matches with the first two elements of a tuple from list1.

list1 = [('google', 'data', '1'), ('google', 'data', '2'), ('google', 'data', '3'), ('google', 'data', '4'), ('google', 'WORLD', '1')]

list2 = [('google', 'data', '1'), ('google', 'HELLO', '2'), ('google', 'BLA', '3')]

Result: list1 = [('google', 'WORLD', '1')]


Solution

  • You can use a list comprehension with all to get only elements that do not match with any of the elements from the second list.

    res = [x for x in list1 if all(x[:2] != y[:2] for y in list2)]