Difference between two lists of lists in Python

Viewed 361

I have two lists of lists:

a = [[1,2,3],[4,5,6],[7,8,9]]
b = [[1,2,3],[9,9,9]]

I would like to get a set difference between them - expected outcome:

c = a - b = [[4,5,6],[7,8,9]].

I tried set() and set.difference() but it seems not to be able to compare lists.

2 Answers

Just use list comprehensions like so:

a = [[1,2,3],[4,5,6],[7,8,9]]
b = [[1,2,3],[9,9,9]]
c = [d for d in a if d not in b]
print(c)

Output:

[[4, 5, 6], [7, 8, 9]]

You can iterate through one and check if it's in the other.

[numbers for numbers in a if numbers not in b]

Related