I am new to python. I am trying to understand the behavior of a function.
I have two arrays:
a_indices, a 5x2 array for which each row contains row and column indices of specific cells of a matrix (not relevant for this question)a_templatea 9x2 array containing values that should be subtracted from each row of 1) in order to get the indices of the neighboring cells
To subtract a_template from each row of a_indices I cooked up the following code:
import numpy as np
# define arrays
a_indices = np.array([[0, 1],[1, 2],[2, 2],[0, 2],[1, 2]])
a_template = np.array([[-1,-1],[-1,0],[-1,1],[ 0,-1],[0, 0],[ 0, 1],[ 1, -1],[ 1, 0],[ 1, 1]])
# add a_template to each row of a_indices
a1 = []
for x in a_indices:
a1.append(np.add(x,a_template))
print(a1)
Starting with an empty list it appends arrays with added values for each row of a_indices. This gives a list of 5 numpy arrays of 2x9, containing the values I need. Good!
However I will produce a lot of these a_indices arrays and they will likely have different numbers of rows. Therefore I wanted to wrap the above for loop into a function that should return my desired objects. So I tried this:
def find_neighbors(idc):
b = []
for x in idc:
b.append(np.add(x,a_template))
return b
a2 = find_neighbors(a_indices)
print(a2)
The function just contains the for loop from the above example. I expected that this function returns the same object as a1. However it returns a list of only one array (the same as the first array from a1).
My question is why does my function not return a list for each row of a_indices and of course how can I fix this?
returnright after the first iteration of your loop.returnoutside of the loop. Indentation is important in Python.