I try use functions as arguments for higher-order programming. Following is an example from a book by John V. Gutttag. The function applyToEach assumes that the first argument 'L' is a list, the second 'f' a function. Output is l= [1, -2, -3.5, 4], l= [1, 2, 3.5, 4],l= [1, 2, 3, 4], as expected.
if I change the second and third line to:
for i in L:
i = f(i)
the output is l= [1, -2, -3.5, 4], three times, which means that i = f(i) won't do any change to the list. How is it?
code:
def applyToEach(L,f):
for i in range(len(L)):
L[i] = f(L[i])
l = [1,-2,-3.5,4]
print('l=',l)
print('apply abs to each element of l')
applyToEach(l,test)
print('l=',l)
print('apply int to each element of l')
applyToEach(l,int)
print('l=',l)