How to compute list difference with Python?

Sometimes, we want to compute list difference with Python.

In this article, we’ll look at how to compute list difference with Python.

How to compute list difference with Python?

To compute list difference with Python, we can use the - operator with sets.

For instance, we write:

A = [1, 2, 3, 4]
B = [2, 5]

x = list(set(A) - set(B))
print(x)

We create sets from A and B with the set functions.

Then we get the difference between the 2 sets with the - operator.

Finally, we convert the returned set difference back to a list with list and assign that to x.

Therefore, x is [1, 3, 4].

Conclusion

To compute list difference with Python, we can use the - operator with sets.