2
def get_thing(item, obj):
  for i in range(item):
    obj.append(i)
  return obj
    
def main():
  thing = []
  get_thing(5, thing)
  print(thing)

main()

I would expect the following code to return

[]

and not

[0,1,2,3,4]

It seems to be working the same way as if I was doing this instead.

thing = get_thing(5, thing)

What is the background process that is going on that results in this kind of return? I noticed this a couple of times in the code at work and was a little perplexed by it and not quite sure how this works.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • 3
    Lists are passed by reference. It's always referring to the same list unless you make a copy. – Random Davis Dec 29 '20 at 18:22
  • Does this answer your question? [List changes unexpectedly after assignment. How do I clone or copy it to prevent this?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent) – Random Davis Dec 29 '20 at 18:22
  • @RandomDavis - useful as a metaphor, but technically incorrect. I think this [answer](https://stackoverflow.com/a/986145/14277722) is more informative. – Michael Szczesny Dec 29 '20 at 18:28
  • Does this answer your question? [How do I pass a variable by reference?](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – Federico Baù Dec 29 '20 at 18:34

1 Answers1

0

Long story short, is because you're passing a mutable object as Argument to the function call.

Do this: NOTE this is only as demonstration purpose

def get_thing(num, lst):

    if not lst:
        lst = []
    for n in range(num):
        lst.append(n)
    print(lst) # [0, 1, 2, 3, 4]
    return lst


def main():
    thing = None
    get_thing(5, thing)
    print(thing) # None


main()

And you can see that it works as you expect.

Stack Overflow related

Documentation

Federico Baù
  • 6,013
  • 5
  • 30
  • 38