10. Question re: return



I'm curious - why do I not have to return x[1] under the function but I have to return x?
If return sends the data back to the original function to "save" it, wouldn't I need to send both back?

For example
def list_function(x):
return x[1]
return x

leads to error whereas if I do just return [x] it's fine

def list_function(x):
    return x 

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


You began slicing at x[1], then added 3 to it. So now x[1] + 3 is stored in x[1].

return x

Now the data from the results of x[1]=x[1]+3 is stored in x. If you did return [x], you're putting it in another list. And gives you extra brackets when printing which the lesson doesn't want. By returning x without brackets, you're leaving it in a single list.


So you're saying by doing the equation with x[1], it automatically saves it in the x[1] spot but doesn't save the entire list until you return x ? I would think if I'm saving x[1] that I'm automatically saving a new x list but I guess that's not the case.

I didn't mean to put the brackets around x so I understand why i wouldn't do return [x]


It does save the list, however if you want to access the list outside of the function you need to return it.

List are mutable, meaning you can change them, you do not create a new list when editing it. Unlike strings, if you edit a string, i.e. using .lower(), you create a new one.


Yes, it saves your list and does the equation in the second part of your x list. When you return it, your function executes, and does the problem for your list.


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