Search code examples
pythonrecursiongloballocalencapsulation

How can i define a shared list in the recursive function in python?


I want to encapsulate my function and define the list in the function, not before it! for example in this code:

s = []
def rec(n):
    if n == 0:
        return s
    else:
        s.append(n)
        rec(n-1)
        return s
print(rec(5))

but when i define it in the recursive function, it become local.


Solution

  • You can do this by pass the list (with a default value) in your recursive function's argument:

    def rec(n, s=[]):
        if n == 0:
            return s
        else:
            s.append(n)
            rec(n-1, s)
            return s
    print(rec(5))