2

I have the following example:

def some_function(input1, some_list=[]):
    if some_list==[]:
        some_list.append(input1)
    if input1 % 3 != 0:
        some_list.append('last_one')
    else:
        some_list.append(input1/3)
        some_list = some_function(input1/3, some_list)
    return some_list

def main():

    #first call
    print(some_function(9))
    #second call
    print(some_function(99))
    return

if __name__ == '__main__':
    main() 

the output is:

[9, 3.0, 1.0, 'last_one']
[9, 3.0, 1.0, 'last_one', 33.0, 11.0, 'last_one']

I don't understand why the local variable "some_list" in the function still has the content from the first call, when it is called a second time. I think it should be initiated and be empty when the second call takes place.

Egirus Ornila
  • 1,234
  • 4
  • 14
  • 39

1 Answers1

2

This is a common problem when you have mutable default arguments.

The usual solution is to default to None and instantiate a new list when needed:

def some_function(input1, some_list=None):
    if some_list is None:
        some_list = []
    ...
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485