I want to subtract two list with the same length such it returns a list with same length, for example,
a = [1,2,3,4]
b = [5,4,3,7]
a-b=[1-5,2-4,3-3,4-7]=[-4,-2,0,-3]
is there any method?
This is a nice use case for list comprehensions + the zip built-in which picks one element of each iterable:
result = [i - j for i, j in zip(a,b)]
In [3]: a = [1,2,3,4]
...: b = [5,4,3,7]
In [4]: [i - j for i, j in zip(a,b)]
Out[4]: [-4, -2, 0, -3]
Going through parts: the usage of a for statement inside the familiar list [ ] delimiters is a long standing Python idiom, inherited directly from mathematical notation: the leftmost expression is evaluated once at each of the for iterations.
The zip callable is a specialized Python built-in to allow one to pick items from different iterables of the same length (by default, the shortest iterable), and make this elements available in a for statement.
So, this will create a new list, with as many elements as the shortest of a and b, with each element being calculated as the difference of the source elements in their respective lists.
Another approach could be casting at least one of the lists to a sequence which implements the - operator as an element by element operator. Numpy arrays do that, for example:
In [2]: import numpy as np
In [3]: a = [1,2,3,4]
...: b = [5,4,3,7]
In [4]: a1 = np.array(a)
In [5]: a1 - b
Out[5]: array([-4, -2, 0, -3])
And finally, installing numpy in a project just for doing this could be overkill, depending on the project's nature - Python's way of working allows one to easily create a 'list like' class which could perform an element by element subtraction, just by implementing the __sub__ special method:
In [3]: a = [1,2,3,4]
...: b = [5,4,3,7]
In [7]: class SubtractableList(list):
...: def __sub__(self, other):
...: return type(self)([i - j for i, j in zip(self, other)])
...:
In [8]: a2 = SubtractableList(a)
In [9]: a2 - b
Out[9]: [-4, -2, 0, -3]
(The calculation itself is performed with the same list comprehension shown on the first example, but the specialized class way allows it to be performed by using the - operator directly now).
As a final remark: although creating your own custom list class in this way is fun, and a nice thing to do, one should either just do it like in this example in throw away scripts, or small scripts that would not grow in complexity and several use cases - a correct sequence class performing this for a larger software project could be more complex to cover edge cases, and work correctly in most cases. So, either use just the plain list comprehension, or if using numpy is not a problem, go for it.