The Python Oracle

Python list subtraction operation

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor

--

Chapters
00:00 Python List Subtraction Operation
00:13 Answer 1 Score 370
00:26 Answer 2 Score 42
00:44 Accepted Answer Score 520
01:22 Answer 4 Score 49
01:34 Thank you

--

Full question
https://stackoverflow.com/questions/3428...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list

#avk47



ACCEPTED ANSWER

Score 520


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   



ANSWER 2

Score 370


Use set difference

>>> z = list(set(x) - set(y))
>>> z
[0, 8, 2, 4, 6]

Or you might just have x and y be sets so you don't have to do any conversions.




ANSWER 3

Score 49


if duplicate and ordering items are problem :

[i for i in a if not i in b or b.remove(i)]

a = [1,2,3,3,3,3,4]
b = [1,3]
result: [2, 3, 3, 3, 4]



ANSWER 4

Score 42


That is a "set subtraction" operation. Use the set data structure for that.

In Python 2.7:

x = {1,2,3,4,5,6,7,8,9,0}
y = {1,3,5,7,9}
print x - y

Output:

>>> print x - y
set([0, 8, 2, 4, 6])