Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why this python function return len=7 instead of len=6?

Tags:

python-3.x

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:

  1. first func call: ipdb> --Return-- ['a']
  2. second func call: ipdb> --Return-- ['a', 'a']
  3. third func call: 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()))
like image 567
tinix84 Avatar asked May 28 '26 07:05

tinix84


1 Answers

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.

like image 187
Kaldrr Avatar answered Jun 04 '26 14:06

Kaldrr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!