Skip to content
Advertisement

*args in Python in combination with numpy.add()

import numpy as np

a = np.array([1.2, 5.4, 6, 1.5, 9])
b = np.array([5.2, 1.0, 1.2, 1.5, 2])


def sum_arrays(*array: np.array):
    return np.add(array)


print(sum_arrays(*a, *b))

Is there a way to add two arrays together with add function, using variable arguments? I know this example is wrong, but it’s just to get the idea

Advertisement

Answer

If all you want to do is add the arrays component-wise, you can use +, which works on numpy arrays.

a + b

Alternatively, as you’ve already pointed out, you can use np.add instead.

np.add(a, b)

If you want to sum all of the elements in both arrays, then again the simplest solution is the best: sum them both separately then add them

a.sum() + b.sum()

There’s no need to use variable arguments here; numpy handles the vectorization for you, and unpacking everything into a Python tuple is just counterproductive.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement