-1

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.]
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 2
    You never iterated over the `map` object. `map(myfun, np.arange(size))` just creates the `map` object, which immediately gets discarded. In any case, it is bad style to use `map` for side effects, but of course, you *can* – juanpa.arrivillaga Apr 27 '22 at 06:25
  • if you change it to ```list(map(myfun, np.arange(size)))``` you get the same result – Nin17 Apr 27 '22 at 06:28

1 Answers1

0

Because map is lazy calculation, when you don't traverse the results of map, map doesn't apply your function to each variable.

Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31