If we define a function that modifies a global variable, and run that function using map(), it fails to make the changes to the variable.
The question is how come there is a difference in behavior compared to simply running inside a for loop?
Minmal working example with for loop:
size = 5
datavals = np.random.random((size,4))
mydict = {'values':np.zeros((size))}
def myfun(index):
v1 = np.sum(datavals[index,:]**2)**0.5
mydict['values'][index] = v1
return
for i1 in np.arange(size):
myfun(i1)
print('function evaluated in for loop')
print(mydict['values'])
Gives the expected output of
function evaluated in for loop
[1.60797084 1.15736358 0.91658427 1.47411556 1.62382541]
However, running the same function in map():
size = 5
datavals = np.random.random((size,4))
mydict = {'values':np.zeros((size))}
def myfun(index):
v1 = np.sum(datavals[index,:]**2)**0.5
mydict['values'][index] = v1
return
map(myfun, np.arange(size))
print('function evaluated using map()')
print(mydict['values'])
shows the variable is not modified:
function evaluated using map()
[0. 0. 0. 0. 0.]