Modifying an element of a list in a function 10/18


I'm not sure whats wrong with this script. The output is exactly what the instructions call for. Maybe its just the specific syntax that the program wants?

def list_function(n):
return n[1] + 3

n = [3, 5, 7]

n[1] = list_function(n) # This essentially represents a 'variable' (list_function), which has been defined (def) to alter the 1st index of the 'n' list above, adding 3 to 5; The unaltered 1st index (n[1]) of the NOT yet defined 'n' list is then equated to this variable to effectively alter the 1st index.

print n

The ERROR: Oops, try again.
list_function([5, 5]) returned 8 instead of [5, 8]

BUT I still get the output: [3, 8, 7]


its because you are supposed to make n[integer] = n[integer] + 3
then your supposed to return n[integer]
try print list_function(n) instead of print n
replace integer with 1


It's important to note that n in global scope is not the same n in local scope when n is a parameter of the function. Were we to have a function like so,

def add_n():
    if len(n)<1:
        return 0
    elif len(n)==1:
        return n[0]
        return sum(n)

n = []
print add_n()     #  0
n += [5,6,7]
print add_n()     #  18

the variable, n is global, not scoped to the function.

This all changes when we gave our parameter the same name, or does it?

def add_nn(n):
    if len(n)<1:
        return 0
    elif len(n)==1:
        return n[0]
        return sum(n)

print add_nn([5,6,9])     #  20

The global; n is no longer visible in the function, is what I was working toward.


I was doing the exact same thing you did. What I had to do was, like mgracer48_55d5eedb91 said, make it x[1] = x[1] + 3. But the third step of the instructions says to Return the list, apparently inside the function, so you have to add the line "return x" too, and NOT "return x[1]". I got thrown off at first bedause I didn't realize it actually meant return the list as a whole and not just that one index


I had the same problem and replacing "return x[1]" with "return x" solved it. The instructions are poorly worded.


When the instructions read, return a list it means what it says. Return a list. x is a list; x[1] is only one member of the list, so is therefore a value, not a list (in this case).