0

Here there's two simple codes I don't understand.

def buggy(arg,result=[]):   
  result.append(arg)
  print(result)
  print('---')

buggy('a')
buggy('b')
buggy('c')
buggy('d')

output:

['a']

['a', 'b']

['a', 'b', 'c']

['a', 'b', 'c', 'd']

def buggy(arg,result=[]):
   if len(result)==0:
       result=[]

   result.append(arg)
   print(result)
   print('---')

buggy('a')
buggy('b')
buggy('c')
buggy('d')

output:

['a']

['b']

['c']

['d']

I think if first code's output is True, the second code's output must to be the same as the first code's output. what happened?

Eric
  • 165
  • 2
  • 7
  • Here it's explained. https://docs.python-guide.org/writing/gotchas/#what-you-wrote – Tom Wojcik Feb 17 '19 at 07:13
  • This explanation is not enough. What exactly I wonder is.... if python’s default arguments are evaluated once when the function is defined, in the second code, list 'result' is ['a'] right before buggy('b') is implemented. so len(result) is not 0 and result is still ['a'] after 'if' statement is implemented. so the output of buggy('b') should be ['a','b'] but it is not! could you please explain about this mismatch. – Eric Feb 17 '19 at 07:30
  • instead of printing `result` print yourself `id(result)` before and after `result=[]`. You create a new pointer in your if statement. If you run `result.clear()` instead of new assignment `result=[]` you will get your expected behavior. Imo a good question :) – Tom Wojcik Feb 17 '19 at 11:02

0 Answers0