2

I was watching a python tutorial video and this function didn't required a return statement

spy = [0,0,7]
def replace_spy(x):
  x[2] = x[2] + 1
replace_spy(spy)
print spy
// it prints [0,0,8]

However, the following code did require a return statement.

def inc(n):
  n = n + 1
  return n
a = 3
inc(a)
print a
// it prints 3

Why doesn't the first example require a return statement like the second example did?

And how come the first example has the function parameter change the value of the object passed in (it changes the value of 'spy' from [0,0,7] to [0,0,8]), whereas the second example has the parameter not change the value of the object passed in but rather refers to a new value ('a' remains 3, and 'n' becomes 4). Can someone please explain? Thanks

  • Try `a = inc(a)`... Ta da! – OneCricketeer Jul 29 '16 at 00:15
  • 3
    The list is changed in place in your first example, its passed to the function by reference (I'm not sure if thats the accepted terminology for it but it serves to illustrate the concept). Where as the `inc` function modifies a local copy of your integer variable `n`, not `a` itself. – Paul Rooney Jul 29 '16 at 00:17
  • Rooney is as correct as he says. It is not accepted terminology to say it is by reference but check this article for a deeper understanding: https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/ – tortal Jul 29 '16 at 01:12

0 Answers0