The nested list comprehension will do the job:
In [102]: [[i2-j2 for i2,j2 in zip(i1,j1)] for i1,j1 in zip(a,b)] Out[102]: [[-4, -4, -4, -4], [-7, 2, 2, 2], [-1, -1, -1, -1, -1]]
The problem with np.array(a)-np.array(b) is that the sublists differ in length, so the resulting arrays are object types - list arrays
In [104]: np.array(a) Out[104]: array([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6, 7]], dtype=object)
Subtracting an iteration over an external array is very simple, but the problem is when subtracting one subscription from another is therefore an error message.
If I made input arrays of arrays, subtraction will work
In [106]: np.array([np.array(a1) for a1 in a]) Out[106]: array([array([1, 2, 3, 4]), array([2, 3, 4, 5]), array([3, 4, 5, 6, 7])], dtype=object) In [107]: aa=np.array([np.array(a1) for a1 in a]) In [108]: bb=np.array([np.array(a1) for a1 in b]) In [109]: aa-bb Out[109]: array([array([-4, -4, -4, -4]), array([-7, 2, 2, 2]), array([-1, -1, -1, -1, -1])], dtype=object)
You cannot count on array operations that work with arrays of dtype objects. But in this case, subtraction is defined for subarrays, so it can handle nesting.
Another way to create nesting is to use np.subtract . This is the ufunc version - and will apply np.asarray to its inputs if necessary:
In [103]: [np.subtract(i1,j1) for i1,j1 in zip(a,b)] Out[103]: [array([-4, -4, -4, -4]), array([-7, 2, 2, 2]), array([-1, -1, -1, -1, -1])]
Note that these array calculations return arrays or a list of arrays. Returning internal arrays to lists requires iteration.
If you start with lists, converting to arrays often does not save time. Array calculation can be faster, but this does not compensate for the overhead of creating arrays in the first place.
If I insert inputs at an equal length, then a simple subtraction of the array is performed, creating a 2d array.
In [116]: ao= [[1,2,3,4,0], [2,3,4,5,0],[3,4,5,6,7]]; bo= [[5,6,7,8,0], [9,1,2,3,0], [4,5,6,7,8]] In [117]: np.array(ao)-np.array(bo) Out[117]: array([[-4, -4, -4, -4, 0], [-7, 2, 2, 2, 0], [-1, -1, -1, -1, -1]])