Modifying an element in a list of a function


#1





Alright, so I have passed this section, but I do not understand why the code works!

I particular do not understand why I have to "return x"!!!
I noticed that if I got rid of the "return x", it gives me the correct answer (by correct I mean the EXACT same answer as when I write "return x"), but the program will give an error message, "Oops, try again. list_function([6, 2]) returned None, did you remember to return the result?"

Why is the first one unacceptable?


SEEMINGLY CORRECT CODE:
def list_function(x):
    x[1] = x[1] + 3
n = [3, 5, 7]
list_function(n)
print n

CORRECT CODE:
def list_function(x):
    x[1] = x[1] + 3
    return x
n = [3, 5, 7]
list_function(n)
print n


#2

this stack overflow question answers your question in detail:

read the first answer, it is great.

In short, because of how python works under the hood, you don't need to return the list, but the exercise demands it of you


#3

I think that makes sense, although it is hard to follow!` Thanks for the response


#4

let me see if you can break it down for you, if you have the following code:

def example(y):
    y += "world"

x="hello"
example(x)
print x

y is a local variable, it only exist inside the function, so if i don't return it, i don't have access to the updated string outside the function.

This make sense right? (lets call this breakpoint 1, does breakpoint1 make sense?)

okay, this line from the stackoverflow question (modified to your code):

In list_function you are modifying (or "mutating") the contents of n but never change what n itself refers to

This is confusing, isn't it? to understand this, you need to understand that the list is stored in memory at an address. We can make a nice analogy, our computer memory is a city, and the address we store the list is your house address.

if we change the door from your house (update an item in the list) the address of your house stays the same, but something has changed (the door)

So if you give your address to two friends (x and n variable), they will both see the modified door (item in list) when they come and visit (retrieving the list)

This is why this works, hopes this helps.


#5

Masterful explanation! Everything makes sense now, I just have to apply it to fully understand.
Thanks stetim94


#6

thank you :slight_smile:

with this i can't help you, good luck!


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.