1

I came across this function where an empty list is passed in as a parameter in the function.

def myFunction(value, values=[]):
    values.append(value)
    return values

myFunction(1)
myFunction(2)
myFunction(3)

The output is:

[1,2,3]

instead of:

[3]

Does this only work for lists? When I tried doing it with just an integer, it does not work.

def myNumber(value, values = 10):
    if value > 100:
        values += 2
        return values
        
myNumber(101)
myNumber(102)
Jessica
  • 243
  • 1
  • 10
  • 1
    https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument and https://softwareengineering.stackexchange.com/questions/157373/python-mutable-default-argument-why – wkl Aug 12 '22 at 15:19
  • This happens for all mutable values, so notably lists, dicts, sets and objects you define. – Filip Müller Aug 12 '22 at 15:19

0 Answers0