How do you subtract elements from a list in python?

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.

In this article, we will learn to perform subtraction on a list in Python. We will use some built-in functions and some custom code as well. Let's first have a quick look over what is list and list subtraction in Python.

Python List

Python has a built-in data type called list. It is like a collection of arrays with different methodology. Data inside the list can be of any type say, integer, string or a float value, or even a list type. The list uses comma-separated values within square brackets to store data. Lists can be defined using any variable name and then assigning different values to the list in a square bracket. The list is ordered, changeable, and allows duplicate values.

list1 = ["Ram","Arun","Kiran"]
list2 = [16,78,32,67]
list3 = [‘apple’,’mango’,16,’cherry’,3.4]

List Subtraction

List subtraction uses two lists and returns a new list after subtraction. This is similar to performing a subtraction operation in mathematics. It finds the difference between each element at each index from the given two lists.

#input
list1 = [4,8,1,9,5]
list2 = [1,4,2,6,7]

#output
list3 = [3,4,-1,3,-2]

New List = Elements of List1 - Elements of List2

To perform list subtraction, the two input lists must be of the same length and it should contain elements of the same type i.e. both lists must contain only numerical values. The given example subtracts the elements at each index in one list from the other list.

Example: List Subtraction Using zip() and "-" operator

This method uses zip(iterator1, iterator2) with the list1 as iterator1 and list2 as iterator2 to return a zip object. It uses a for-loop to iterate over the zip object and subtract the lists' elements from each other and store the result in a new list.

#takes two input lists
list1 = [4, 8, 1, 9, 5]
list2 = [1, 4, 2, 6, 7]

#empty list
sub_list = []

#two lists are passed to zip 
zip_object = zip(list1, list2)

#loop to find diff of each element
for list1_i, list2_i in zip_object:
    sub_list.append(list1_i - list2_i)

print(sub_list)


[3, 4, -1, 3, -2]

Conclusion

In this article, we learned to find the difference between each element of two lists by traversing them using a zip object. We learned to perform list subtraction over each element.

How do you subtract a number from all elements of a list?

subtract Items from a list.
Enter element to a list..
Add the list elements and subtract the last element: Example: List items; {100, 50, 1}. 100 + 50 = 150, 150-1..
Subtract the elements from the list: 100 - 50 = 50, 50 - 1 = 49..

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.

How do you subtract two elements from an array in Python?

subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise. Parameters : arr1 : [array_like or scalar]1st Input array.

How do you do a subtraction formula 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.