The goal is to compute the difference between two lists, x and y, resulting in a new list containing elements from x that are not present in y.
To preserve the original order from x, use a list comprehension to check which elements are not in y:
<code class="python">[item for item in x if item not in y]</code>
If the order of elements in the resulting list is not important, a set difference can be employed:
<code class="python">list(set(x) - set(y))</code>
To enable the infix x - y syntax for list subtraction, a custom class can be created that overrides the __sub__ method to implement the desired behavior:
<code class="python">class MyList(list): def __sub__(self, other): return self.__class__(*[item for item in self if item not in other])</code>
With this class, the subtraction can be performed as follows:
<code class="python">x = MyList(1, 2, 3, 4) y = MyList(2, 5, 2) z = x - y </code>
The above is the detailed content of How to Compute the Difference Between Two Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!