[SOLVED] Replace for loop that indexes two arrays and applies a function on each row

Issue

I have a for-loop that works on two values and I would like to apply it in a faster way or vectorise it if possible. My original for-loop looks something like this

import numpy as np

x = [1,2,3]
y = [0,0,0]

for i in range(len(x)):
    
    # index value in each element
    xi = x[i]
    yi = y[i]
    
    # apply function some bivariate function
    print(np.sum(xi,yi))

I was thinking maybe I could use the list approach but the output came out as below.

x = [1,2,3]
y = [0,0,0]

[np.sum(i, j) for i in x for j in y]
# output
[1, 1, 1, 2, 2, 2, 3, 3, 3]

What are better methods to replace the initial for-loop statement? My actual function is not a sum as in the initial example, that is just a dummy function.

Solution

IIUC, use zip

>>> [np.sum(i, j) for i, j in zip(x, y)]
[1, 2, 3]

Answered By – Corralien

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.