Home >Backend Development >Python Tutorial >How to Compute the Difference Between Two Lists in Python?

How to Compute the Difference Between Two Lists in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 14:40:06336browse

How to Compute the Difference Between Two Lists in Python?

Subtraction of Lists

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.

Solution 1: List Comprehension

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>

Solution 2: Set Difference

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>

Solution 3: Overriding sub

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn