Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list subtraction operation

Tags:

python

list

I want to do something similar to this:

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

But this is not supported by python lists What is the best way of doing it?

like image 780
daydreamer Avatar asked Aug 06 '10 23:08

daydreamer


People also ask

Is there a subtraction function in Python?

To subtract two numbers in Python, use the subtraction(-) operator. The subtraction operator (-) takes two operands, the first operand on the left and the second operand on the right, and returns the difference of the second operand from the first operand.

Can you subtract one list from another in Python?

Method 3: Use a list comprehension and set to Find the Difference Between Two Lists in Python. In this method, we convert the lists into sets explicitly and then simply reduce one from the other using the subtract operator.


2 Answers

Use a list comprehension:

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

If you want to use the - infix syntax, you can just do:

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]) 

you can then use it like:

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

But if you don't absolutely need list properties (for example, ordering), just use sets as the other answers recommend.

like image 188
aaronasterling Avatar answered Sep 28 '22 20:09

aaronasterling


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.

like image 31
quantumSoup Avatar answered Sep 28 '22 21:09

quantumSoup