I know subtraction of lists is not supported in python, however there are some ways to omit the common elements between two lists. But what I want to do is subtraction of each element in one list individually with the corresponding element in another list and return the result as an output list. How can I do this?
A = [3, 4, 6, 7]
B = [1, 3, 6, 3]
print A - B #Should print [2, 1, 0, 4]
subtract two lists using Zip() Function In this method, we'll pass the two input lists to the Zip Function. Then, iterate over the zip object using for loop. On every iteration, the program will take an element from list1 and list2, subtract them and append the result into another list.
To check if two lists are equal in Python, use Equal to comparison operator. If two lists are equal, then equal to operator returns True, else it returns False. list1 = [12, 8, 4, 6] list2 = [12, 8, 4, 6] if list1 == list2: print('list1 and list2 are equal. ') else: print('list1 and list2 are not equal.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With