List manipulation in functions


List manipulation in functions

Oops, try again. list_extender([1, 2, 3, 4]) returned None, did you remember to return the result?

why I can't put n.append(9) & return n together to be return n.append(9) ?


n = [3, 5, 7]
# Add your function here

def list_extender(n):
    return n.append(9)

print list_extender(n)


You can. But do you want to return the value that the append method returns? If not, then you probably shouldn't.


Well, thanks for your reply firstly.
However, I'm afraid I actually don't get your point,
Could you mind using some cases to explain differences between those ?
Thanks anyway


You're asking why you can't return the result of calling your list's append method.

You can, so there is no "why not".

But is the value that it returns what your function should return? If it's a different value, then you should not return that value.

If you have 5 and 7, and your function is supposed to return 5, then you can return 7, but 7 is not the value that your function should return, so you should probably return 5 instead. Asking why 7 can't be returned doesn't have an answer, because it can be returned.


Well, OK, now I know what your mean
So how about if I want to return the value that the append method returns.
it should return [3, 5, 7, 9], shouldn't it ?
Gosh, I feel like I'm an idiot, sorry bro QQ


Check the function definition for append. The return value for an append function call is None and that is why you get None back. You would have to split it into two lines - 1st line append and 2nd line return the appended list. It seems weird coming from JS or other languages, but that is how Python works! I was put off by this initially when I learnt Python. When in doubt, go to a python interpreter and type help(list.append) to find more details.


Some functions only have a side effect, others have no side effect and return a new value instead. Some might return the same object that its parameter referred to, others might return information about what it did.
As @allentv says, one just has to look it up. Not much point in trying to remember it all either. The things you have to look up a lot will stick.


Oh, I see and feel so sorry to bother you guys for ages. :sob:


ionatan : Now I see and truly thank you for your patience. :grin: Also, feel so sorry to bother you guys for a long time. :sweat: Have a good day !


Nothing to apologize for here, sometimes it takes a few cycles just to refine the question.


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