Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: difference between map() and for loop when handling a function that edits a local variable

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.]

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading