0

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)
Annie
  • 1
  • 1
  • The code works for me as expected, I've only replaced `test` with `abs` – koPytok Jul 17 '18 at 09:09
  • yes it should be abs instead of test. I used 'abs' in my code. The outcome when replaced with ' i = f(i) ' is [1, -2, -3.5, 4], three times. – Annie Jul 17 '18 at 10:32

0 Answers0