2
def incr(s,a=[]):
    for x in s:
        a.append(x)
    return a

print(incr('asmuel'))
print(incr('rainfi'))

Output:
['a', 's', 'm', 'u', 'e', 'l']
['a', 's', 'm', 'u', 'e', 'l', 'r', 'a', 'i', 'n', 'f', 'i']

Why is this function retaining the value even after setting the default parameter to be empty list? How to use the default parameter value i.e [] every time I call the function?

eastwood4
  • 19
  • 4

1 Answers1

0

You should avoid using passing mutable parameters to function. a is not initialized to [] every time you call the function rather just once. The same array is reused in the next function calls. Hence the array just keeps extending

The correct way of doing this is

def incr(s,a=None):
    if a is None:
        a=[]
    for x in s:
        a.append(x)
    return a

This is not only true for a list but for any mutable data structure.

  • i personally prefer doing it like this : `def incr(s,a=()): a = list(a)` or with `a = [*a]` which is a bit more efficient with list that aren't that big – Nenri Feb 05 '20 at 13:54