pythonlist

How do I subtract one list from another?


I want to take the difference between lists x and y:

>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [1, 3, 5, 7, 9]  
>>> x - y
# should return [0, 2, 4, 6, 8]

Solution

  • Use a list comprehension to compute the difference while maintaining the original order from x:

    [item for item in x if item not in y]
    

    If you don't need list properties (e.g. ordering), use a set difference, as the other answers suggest:

    list(set(x) - set(y))
    

    To allow x - y infix syntax, override __sub__ on a class inheriting from list:

    class MyList(list):
        def __init__(self, *args):
            super(MyList, self).__init__(args)
    
        def __sub__(self, other):
            return self.__class__(*[item for item in self if item not in other])
    

    Usage:

    x = MyList(1, 2, 3, 4)
    y = MyList(2, 5, 2)
    z = x - y