Python list subtraction operation

python subtract value from list
python subtract two lists from each other
python list difference between elements
python difference between two lists
python compare two lists element wise
how to compare two lists in python and return non matches
python compare two lists of strings
compare two lists python

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?

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.

How to subtract two lists in Python, How to subtract two lists in Python. list1 = [2, 2, 2] list2 = [1, 1, 1] difference = [] initialization of result list. zip_object = zip(list1, list2) for list1_i, list2_i in zip_object: difference. append(list1_i-list2_i) append each difference to list. print(difference) Python 2.7+ and 3.0 have collections.Counter (a.k.a. multiset). The documentation links to Recipe 576611: Counter class for Python 2.5:. from operator import itemgetter from heapq import nlargest from itertools import repeat, ifilter class Counter(dict): '''Dict subclass for counting hashable objects.

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.

Python, In this method we convert the lists into sets explicitly and then simply reduce one from the other using the subtract operator. For more reference on set visit Sets  Kite is a free autocomplete for Python developers. Code faster with the Kite plugin for your code editor, featuring Line-of-Code Completions and cloudless processing.

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


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

numpy.subtract() in Python, How do you compare two lists in python and return Non matches? Addition Subtraction Multiplication Division in Python. To perform addition, subtraction, multiplication and division in python, you have to ask from user to enter any two number, and then ask again to enter the operator to perform the desired operation. After performing the desired operation, print the result as output.

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]

Difference Between Two Lists using Python Set & Without Set, Given two list, If element in first list in greater than element in second list, then subtract it, else return the element of first list only. Examples: Input: l1 = [10, 20, 30,  Within this Python Program to Perform Arithmetic Operations on Lists example, NumList1 = [10, 20, 30], NumList2 = [5, 2, 3] For Loop – First Iteration: for 0 in range (3) – Condition is True. add.append ( NumList1 [0] + NumList2 [0]) => add.append (10 + 5) add [0] = 15. sub.append ( 10 – 5) => sub [0] = 5. multi.append (10 * 5) => multi [0] = 50.

For many use cases, the answer you want is:

ys = set(y)
[item for item in x if item not in ys]

This is a hybrid between aaronasterling's answer and quantumSoup's answer.

aaronasterling's version does len(y) item comparisons for each element in x, so it takes quadratic time. quantumSoup's version uses sets, so it does a single constant-time set lookup for each element in x—but, because it converts both x and y into sets, it loses the order of your elements.

By converting only y into a set, and iterating x in order, you get the best of both worlds—linear time, and order preservation.*

However, this still has a problem from quantumSoup's version: It requires your elements to be hashable. That's pretty much built into the nature of sets.** If you're trying to, e.g., subtract a list of dicts from another list of dicts, but the list to subtract is large, what do you do?

If you can decorate your values in some way that they're hashable, that solves the problem. For example, with a flat dictionary whose values are themselves hashable:

ys = {tuple(item.items()) for item in y}
[item for item in x if tuple(item.items()) not in ys]

If your types are a bit more complicated (e.g., often you're dealing with JSON-compatible values, which are hashable, or lists or dicts whose values are recursively the same type), you can still use this solution. But some types just can't be converted into anything hashable.

If your items aren't, and can't be made, hashable, but they are comparable, you can at least get log-linear time (O(N*log M), which is a lot better than the O(N*M) time of the list solution, but not as good as the O(N+M) time of the set solution) by sorting and using bisect:

ys = sorted(y)
def bisect_contains(seq, item):
    index = bisect.bisect(seq, item)
    return index < len(seq) and seq[index] == item
[item for item in x if bisect_contains(ys, item)]

If your items are neither hashable nor comparable, then you're stuck with the quadratic solution.

* Note that you could also do this by using a pair of OrderedSet objects, for which you can find recipes and third-party modules. But I think this is simpler.

** The reason set lookups are constant time is that all it has to do is hash the value and see if there's an entry for that hash. If it can't hash the value, this won't work.

Python, It dawned on me today: I'll add lists on a regular basis (listC = listA + listB), but I don't Posted on my Python Wiki too. listC = list(set(listB). intersection(listA)) Addition and Subtraction. In Python, addition and subtraction operators perform just as they do in mathematics. In fact, you can use the Python programming language as a calculator. Let’s look at some examples, starting with integers: print(1 + 5)

How to subtract a list from a list inPython?, The minus operator is defined for sets as the set difference. if. A = set([1, 2, Because - to subtract a list B from list A, don't you want to write C = A - B ? Of course  Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in the binary format their values will be 0011 1100 and 0000 1101 respectively. Following table lists out the bitwise operators supported by Python language with an example each in those, we use the above two variables (a and b) as operands −

How to evaluate one list minus another in Python, If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword  The first argument is the index of the element before which to insert, so a.insert (0, x) inserts at the front of the list, and a.insert (len (a), x) is equivalent to a.append (x). list.remove(x) Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.

numpy.subtract - Numpy and Scipy, Operations with lists are quite common, so in this recipe, we will show you how to add two lists or subtract one list from another. Getting ready. We will use IEx for 

  • @ezdazuzena this is not substraction. This is the difference between two lists. Your sharing is not a dublication of this question.
  • What should [2, 2] - [2] return? []? [2]?
  • @McKay [2,2] - [2] should return [2]. [2,2] - [1,2,2,3] should return []
  • This question is about list subtraction but the accepted answer is closer to set subtraction.
  • What should [2, 1, 2, 3, 2, 4, 2] - [2, 3, 2] return, and why? Should it find the 232 in the middle and return 2142? or should it find the first each time and return 1242? Or something else? What I'm saying is that these are not obvious answers and depend on need.
  • @admica, don't use list for variable names as it shadows the list constructor. If you do use 'list', please precede it with an underscore. Also, by dropping the *, you broke my code...
  • If you do [1,1,2,2] - [1,2] you will get empty list. [1,1,2,2] - [2] gives [1,1] So it is not really list substraction, it is more like "List from List X without elements from set Y".
  • @AlfredZien what he said
  • The list comprehension method is way slower (in my example) than the set difference method.
  • @BarnabasSzabolcs: That won't save a thing, because it will convert y to a set before every check (which is similar cost to original work). You'd need to either do yset = set(y) outside the listcomp, then test if item not in yset, or as an egregious hack, do [item for yset in [set(y)] for item in x if item not in yset] which abuses nested listcomps to cache the yset as a one-liner. A slightly less ugly one-liner solution that performs adequately would be to use list(itertools.filterfalse(set(y).__contains__, x)) because the argument to filterfalse is only constructed once.