1

I have a function with one default argument. This default argument is updated inside the function. When I call the same function again, I see the argument takes the value which is set during the first call

What's wrong with the following code.

def fun(x, data=[]):
    print "entering fun with data = ",data
    data.append(x)

print "calling fun..."
fun(1)
print "calling fun..."
fun(3)

Here the output is

calling fun...
entering fun with data =  []
calling fun...
entering fun with data =  [1]

but I expect the output to be

enter code here
calling fun...
entering fun with data =  []
calling fun...
entering fun with data =  []
Sumit
  • 21
  • 2
  • Why is data an empty list by default? – SuperStew Jan 17 '18 at 18:07
  • The actual scenario is a function which recursively called itself with updated value of data argument. What I see is when I called the same function again from main, I see the data is not empty list but the value which is set during first function call – Sumit Jan 17 '18 at 18:10
  • Yes, this is a common Python gotcha. Read the answers at the linked duplicate – juanpa.arrivillaga Jan 17 '18 at 18:17
  • Sorry, I cannot see the linked duplicate with same issue – Sumit Jan 17 '18 at 18:24

0 Answers0