1

Below are two different functions implemented in Python3.7 and their output of running them 2 times. I believe the biggest difference is the mutable and immutable of the default argument value but why tmp is not an empty list in the second call to function f?

Function 1

def f(tmp=[]):
    print(tmp)
    for i in range(4):
        tmp.append(i)
    return tmp

print(f())
print(f())

Output:

[]
[0, 1, 2, 3]
[0, 1, 2, 3]
[0, 1, 2, 3, 0, 1, 2, 3]

Function 2

def p(a=1):
    print(a)
    a += 1
    return a

print(p())
print(p())

Output:

1
2
1
2
Jack Wang
  • 13
  • 2
  • This does not look like intended behaviour, maybe tell the python core team about this, ima try it in their web interface to see if it is in the newest version. – DownloadPizza Oct 12 '19 at 16:59
  • [“Least Astonishment” and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) This question explains why. – Jack Wang Oct 12 '19 at 17:01

0 Answers0