10.Modifying an element of a list in a function


#1



10. Modifying an element of a list in a function


I keep getting messages which are along the lines of this: Oops, try again. list_function([3, 3]) returned 6 instead of [3, 6]. Can someone please help me find the correct code?


def list_function(x):
    key = x[1]+3
    x[1] = key
    return x[1]

n = [3, 5, 7]
list_function(n)
print n


#2

It appears the function is intended to modify an object, a list. Your first two steps do the modification, but then you return a value, rather than the expected reference object, a list.

If we study this closely we see that x IS n, regardless the local name change. It is still the very object in whatever scope it happens to be. Reference objects are not copied into parameters, just given a local name.

So your code to run the function without expecting a return is perfectly valid, and does work. It's just not what the SCT expects, one would suppose.

return x

#4

Thank you! This is the step that I was missing.


#5