When I write this code and then write add_two_cents(mylist)
into the interactive shell, I am not getting anything back. It just moves on to the next line.
mylist = ["kiwi", "apple"]
def add_two_cents(mylist):
mylist.append("two cents")
When I write this code and then write add_two_cents(mylist)
into the interactive shell, I am not getting anything back. It just moves on to the next line.
mylist = ["kiwi", "apple"]
def add_two_cents(mylist):
mylist.append("two cents")
You aren't returning anything so it prints nothing in interpreter. But lists are mutable so you don't have to return if you don't want to, but if you want to see the change you'll need to print the list. Note I've renamed mylist usage outside the function to make it clear which is a function variable and which is the native variable.
def add_two_cents(mylist);
mylist.append("two cents")
pass #just to point out end of function
foo = ["kiwi", "apple"]
add_two_cents(foo)
print(str(foo)) # this will print a string representation of foo
First of all, if you omit return
in your function, it's the same as writing return None
. So your function does return None
but you don't see that, because by default None
doesn't show up in the interactive REPL shell. That's why you don't see anything.
Furthermore, if you want to see something, you probably want to see your modified list. So you should add return mylist
at the end of your function.
Finally, as mylist
is of type list
, you're changing a mutable and don't really need to return the list at all. Just print it again, to see that it changed.
mylist = ["kiwi", "apple"]
def add_two_cents(mylist):
mylist.append("two cents")
return mylist
You just needed to at the "return" statement