Python List Subtraction Operation

Python list subtraction operation

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.

Subtracting two lists in Python

Python 2.7 and 3.2 added the collections.Counter class, which is a dictionary subclass that maps elements to the number of occurrences of the element. This can be used as a multiset. You can do something like this:

from collections import Counter
a = Counter([0, 1, 2, 1, 0])
b = Counter([0, 1, 1])
c = a - b # ignores items in b missing in a

print(list(c.elements())) # -> [0, 2]

As well, if you want to check that every element in b is in a:

# a[key] returns 0 if key not in a, instead of raising an exception
assert all(a[key] >= b[key] for key in b)

But since you are stuck with 2.5, you could try importing it and define your own version if that fails. That way you will be sure to get the latest version if it is available, and fall back to a working version if not. You will also benefit from speed improvements if if gets converted to a C implementation in the future.

try:
from collections import Counter
except ImportError:
class Counter(dict):
...

You can find the current Python source here.

How to mathematically subtract two lists in python?

Use operator with map module:

>>> A = [3, 4, 6, 7]
>>> B = [1, 3, 6, 3]
>>> map(operator.sub, A, B)
[2, 1, 0, 4]

As @SethMMorton mentioned below, in Python 3, you need this instead

>>> A = [3, 4, 6, 7]
>>> B = [1, 3, 6, 3]
>>> list(map(operator.sub, A, B))
[2, 1, 0, 4]

Because, map in Python returns an iterator instead.

do list subtraction in python

You can easily do this with a list comprehension:

nl = [elem for elem in a if elem not in b]

Edit

Better to use a set to test against. This will remove duplicates from your list.

bb= set(b)
nl = [elem for elem in a if elem not in bb]

Subtract 2 lists by duplicate elements in python

You can do a list comprehension..

[x for x in listA if x not in listB]

Subtracting one list from another in Python

Just use it like that :

 c = [x for x in a if x not in b]

Subtracting 2 lists in Python

If this is something you end up doing frequently, and with different operations, you should probably create a class to handle cases like this, or better use some library like Numpy.

Otherwise, look for list comprehensions used with the zip builtin function:

[a_i - b_i for a_i, b_i in zip(a, b)]


Related Topics



Leave a reply



Submit