-2

I have the following code:

def my_function(x, l=[]):
    for i in range(x):
        l.append(i+i)
    print(l)

my_function(2)
my_function(3)

For the first function call it prints [0,2] which is ok, but then for the second call it prints [0,2,0,2,4]!!! Why? I expected it to be only [0,2,4] since my second argument (or the absence of it) is an empty list. Am I doing something wrong? Am I assuming something wrong? Any help will be greatly appreciated.

Alexis
  • 2,104
  • 2
  • 19
  • 40

1 Answers1

1

It's printing that because the list object does not change between function calls. Try creating a new list object for each call like in the following modified code:

def my_function(x, l):
    for i in range(x):
        l.append(i+i)
    print(l)

my_function(2, list())
my_function(3, list())
Will Hensel
  • 36
  • 1
  • 4