0

Consider the code below. It involves application of a very interesting python concept of using default argument during recursion[reversing a list] A = [1,2,3,4]

def recur(A,Q=[]): 
    if len(A)==1: 
        Q.append(A[0])
        return 
    recur(A[1:],Q)
    Q.append(A[0])
    return Q
print(recur(A)) # 4 3 2 1

Issue is, when I call this function again, Q will not be empty. Is there a way I can set Q=[] when this recursive call finishes ?

NOTE: my intent is not to reverse a list, it's just for demonstration. Thanks

petezurich
  • 9,280
  • 9
  • 43
  • 57
  • 1
    Does this answer your question? ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) – ti7 Jul 21 '22 at 05:56
  • 1
    Yes it does. I remember I learned about this fact from this link only, but couldn't find it again. thanks a lot! – Ayan Srivastava Jul 21 '22 at 14:07

2 Answers2

1

When you first run the script, you're initializing and making Q immutable, regardless of calling the function or future input. You'll need to recreate Q as a new list every time within the function.

Try this:

def recur(A,Q=None):
    if Q == None:
        Q = []
    if len(A)==1: 
        Q.append(A[0])
        return 
    recur(A[1:],Q)
    Q.append(A[0])
    return Q

print(recur([4, 3, 2, 1])) # 1 2 3 4
print(recur([1, 2, 3, 4])) # 4 3 2 1
petezurich
  • 9,280
  • 9
  • 43
  • 57
HWW
  • 114
  • 6
0

Or completely without a default arg:

def _recur(A, Q):
    ...

def recur(A):
    return _recur(A, [])
VPfB
  • 14,927
  • 6
  • 41
  • 75