Skip to content
Advertisement

How to remove from these 2 lists of lists the possible lists that appear in both lists of lists?

These are the two lists, both of which have the same number of elements:

list1 = [['23', '30', 'pm'], ['01', '00', 'am'], ['1', '00', 'am'], ['1', '00', 'pm'], ['1', '', 'pm'], ['5', '', 'pm']]

list2 = [['23', '30', 'pm'], ['01', '00', 'am'], ['01', '00', 'am'], ['01', '00', 'pm'], ['01', '00', 'pm'], ['05', '00', 'pm']]

I try with this:

list1 = list(list1 - list2)
list2 = list(list2 - list1)

print(repr(list1))
print(repr(list2))

but I get this error when trying to subtract the elements that are the same in both lists

TypeError: unsupported operand type(s) for -: 'list' and 'list'

I need the lists to be like this, that is, within each of them there are only those elements that are different:

list1 = [['1', '00', 'am'], ['1', '00', 'pm'], ['1', '', 'pm'], ['5', '', 'pm']]

list2 = [['01', '00', 'am'], ['01', '00', 'pm'], ['01', '00', 'pm'], ['05', '00', 'pm']]

How could I achieve this? (if possible without using additional libraries, although if there is no other way I would have no problem using them)

Advertisement

Answer

You should use zip to iterate the lists in parallel, and another zip to separate the output back in two lists:

l1,l2 = map(list, zip(*((a,b) for a,b in zip(list1, list2) if a!=b)))

Output:

# l1
[['1', '00', 'am'], ['1', '00', 'pm'], ['1', '', 'pm'], ['5', '', 'pm']]

# l2
[['01', '00', 'am'], ['01', '00', 'pm'], ['01', '00', 'pm'], ['05', '00', 'pm']]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement