10. Modifying an element of a list in a function


What the ■■■■, the following is giving me this error:

list_function([0, 2]) returned 5 instead of [0, 5]

and the output on the console is 8 as excepted.

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

n = [3, 5, 7]

print list_function(n)


You want to return the whole list (x), not just the item at index 1 (x[1])


Why would you need to return the whole list instead of just the first index? The code still follows the instructions, right?


well, you want to update the item at index 1 (the second item), but you do want to keep your whole list, so you want to return the whole list. Otherwise, you have one updated value, but without the rest of the list


Why would that be a problem, though, only updating/returning one value?


lets say the list contains my grade, and you want to update one of my grades, i wouldn't be really happy that the rest of my marks/grades are gone

You don't want to loose data. If you just one item, the old list remains, in which case i would complain my mark/grade isn't updated.

There is a huge difference between updating one value, and returning one value instead of the whole list