I got this code below, but even debugging it, I cannot understand why gives me out 7 instead of 6.
More precisely when I debudg every return gives me the expected result:
ipdb> --Return-- ['a']ipdb> --Return-- ['a', 'a']ipdb> --Return-- ['a', 'a', 'a']but at the end func() + func() + func() becomes ['a', 'a', 'a', 'a', 'a', 'a', 'a']
why is there one 'a' more???
#!/usr/bin/python
# -*- coding: utf-8 -*-
def func(par=[]):
par.append("a")
return par
print(len(func() + func() + func()))
When executing func() + func() + func(), Python has to store the temporary objects on the stack to add them together, it means that your code is equivalent to
a = func() # returns ['a']
b = func() # returns ['a', 'a'], but variable 'a' now holds ['a', 'a'] as well!
tmp = a + b
c = func() # return ['a', 'a', 'a']
d = tmp + c
return d
Because of the Mutable Default Argument, before actually adding a+b, both a and b are equal to ['a', 'a'], giving you ['a', 'a', 'a', 'a'], 4 elements, then you add ['a','a','a'] you got from the 3rd func() call, and you get 7 elements as a result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With