-2

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")
finefoot
  • 9,914
  • 7
  • 59
  • 102
ctshea
  • 19
  • 3
    Because your function doesn't return anything. – erip Mar 04 '20 at 23:01
  • Though it's not formatted as code, it doesn;t appear that your function has a `return` statement, so it wouldn't return anything. You also don't appear to be calling the function anywhere. Can you be more specific about your expectation? – G. Anderson Mar 04 '20 at 23:01
  • What are you expecting to happen after you call the function? The function does not return anything but the mylist variable gets modified. – Adolfo Mar 04 '20 at 23:02
  • `list.append` https://docs.python.org/2/tutorial/datastructures.html#more-on-lists does not return anything but append an item to an existing list. – mrzo Mar 04 '20 at 23:02

3 Answers3

2

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
UpAndAdam
  • 4,515
  • 3
  • 28
  • 46
2

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.

finefoot
  • 9,914
  • 7
  • 59
  • 102
0
mylist = ["kiwi", "apple"]
def add_two_cents(mylist):
   mylist.append("two cents")
   return mylist

You just needed to at the "return" statement

Daniel Saggo
  • 108
  • 1
  • 9