0

Default Argument is not working in my case.

if I specify the argument, then it works. but otherwise, It's different from what I expected before.

def splitInteger(a, rtn = []):
    rtn.insert(0, a % 10)
    if(a >= 10):
        return splitInteger(int(a/10), rtn)
    else:
        return rtn

if __name__ == "__main__":
    for i in range(3, 20):
        rtn = splitInteger(i)
        print(rtn)

What I expected was

[3]
[4]
[5]
[6]
[7]
[8]
[9]
[1, 0]
[1, 1]
[1, 2]
[1, 3]
[1, 4]
[1, 5]
[1, 6]
[1, 7]
[1, 8]
[1, 9]

But the output is

[3]
[4, 3]
[5, 4, 3]
[6, 5, 4, 3]
[7, 6, 5, 4, 3]
[8, 7, 6, 5, 4, 3]
[9, 8, 7, 6, 5, 4, 3]
[1, 0, 9, 8, 7, 6, 5, 4, 3]
[1, 1, 1, 0, 9, 8, 7, 6, 5, 4, 3]
[1, 2, 1, 1, 1, 0, 9, 8, 7, 6, 5, 4, 3]
[1, 3, 1, 2, 1, 1, 1, 0, 9, 8, 7, 6, 5, 4, 3]
[1, 4, 1, 3, 1, 2, 1, 1, 1, 0, 9, 8, 7, 6, 5, 4, 3]
[1, 5, 1, 4, 1, 3, 1, 2, 1, 1, 1, 0, 9, 8, 7, 6, 5, 4, 3]
[1, 6, 1, 5, 1, 4, 1, 3, 1, 2, 1, 1, 1, 0, 9, 8, 7, 6, 5, 4, 3]
[1, 7, 1, 6, 1, 5, 1, 4, 1, 3, 1, 2, 1, 1, 1, 0, 9, 8, 7, 6, 5, 4, 3]
[1, 8, 1, 7, 1, 6, 1, 5, 1, 4, 1, 3, 1, 2, 1, 1, 1, 0, 9, 8, 7, 6, 5, 4, 3]
[1, 9, 1, 8, 1, 7, 1, 6, 1, 5, 1, 4, 1, 3, 1, 2, 1, 1, 1, 0, 9, 8, 7, 6, 5, 4, 3]

As you can see above, I didn't pass any argument to the second parameter, so I thought like It will receive empty array automatically.

Can you tell me why this thing happens?

Antonio SEO
  • 457
  • 1
  • 9
  • 23
  • 1
    This is a very common issue, see [this](https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments). – iz_ Jan 09 '19 at 04:35

1 Answers1

1

It's because your splitInteger is modifying rtn everytime it is called.

# First iteration
splitInteger(1)
# [1]
# but now, rtn = [1] 
# Second iteration
splitInteger(1)
# [1, 1]

Making a new list inside a function will solve your problem

def splitInteger(a, rtn = []):
    r = rtn.copy() 
    r.insert(0, a % 10)
    if(a >= 10):
        return splitInteger(int(a/10), r)
    else:
        return r

Results:

for i in range(3, 20):
    rt = splitInteger(i)
    print(rt)

[3]
[4]
[5]
[6]
[7]
[8]
[9]
[1, 0]
[1, 1]
[1, 2]
[1, 3]
[1, 4]
[1, 5]
[1, 6]
[1, 7]
[1, 8]
[1, 9]
Chris
  • 29,127
  • 3
  • 28
  • 51