List Difference | The Most Pythonic Way

Short answer: The most Pythonic way to compute the difference between two lists l1 and l2 is the list comprehension statement [x for x in l1 if x not in set(l2)]. This works even if you have duplicate list entries, it maintains the original list ordering, and it’s efficient due to the constant runtime complexity of the set membership operation.

What’s the best way to compute the difference between two lists in Python?

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

# a – b == [3, 2, 1]
# b – a == [6, 7]

In Python, you always have

Continue reading the original article