-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
  • 1,696
  • 1
  • 11
  • 33
  • This is a consequence of using a mutable data type as a default argument. – ddejohn Jun 04 '22 at 03:21
  • 1
    But why downvotes? – j1-lee Jun 04 '22 at 03:23
  • @j1-lee How many times can this be asked before you consider asking it again not useful? The "least astonishment" one in particular is the seventh-most duplicated Python question of all time, with 987 duplicates. – Kelly Bundy Jun 04 '22 at 03:41

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())