Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mathematically subtract two lists in python? [duplicate]

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]
like image 799
Gareth Bale Avatar asked Apr 19 '14 17:04

Gareth Bale


People also ask

How do you subtract one list from another list?

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.

How do I compare two identical lists?

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.


1 Answers

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.

like image 192
Thanakron Tandavas Avatar answered Sep 30 '22 03:09

Thanakron Tandavas