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'
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]
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]
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