Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List substraction in python

Tags:

python

list

Suppose I have two lists of different length.

a = [8,9,4,7,5,6,1,4,8]
b = [6,4,7,1,5,8,3,6,4,4]

I want a list like this:

c= a-b

#output = [2, 5, -3, 6, 0, -2, -2, -2, 4]

How can i achieve this?

I tried operator.sub with map function. But I am getting an error because of different lengths of list.

c = map(operator.sub, a, b)

TypeError: unsupported operand type(s) for -: 'NoneType' and 'int'

like image 433
Dheeraj Avatar asked Dec 19 '22 08:12

Dheeraj


2 Answers

You may use zip along with list comprehension expression as:

>>> a = [8,9,4,7,5,6,1,4,8]
>>> b = [6,4,7,1,5,8,3,6,4,4]

>>> [x - y for x, y in zip(a, b)]
[2, 5, -3, 6, 0, -2, -2, -2, 4]
like image 141
Moinuddin Quadri Avatar answered Jan 02 '23 17:01

Moinuddin Quadri


from itertools import starmap
from operator import sub

a = [8,9,4,7,5,6,1,4,8]
b = [6,4,7,1,5,8,3,6,4,4]

output = list(starmap(sub, zip(a, b)))

If you do not want to use a list comprehension, this can be done with itertools.starmap.

You could also use map, though I think starmap is the better option. With map you could use a nested zip to shorten the longer argument.

output = map(sub, *zip(*zip(a, b)))
print(list(output))
# [2, 5, -3, 6, 0, -2, -2, -2, 4]
like image 34
Tristan Avatar answered Jan 02 '23 15:01

Tristan