简体   繁体   中英

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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM