I have a question about how Python return value. Below is my simple python code practicing recursive function.
def brackets(ans, n, cur, open, close):
if len(cur) == n*2:
ans.append(cur) # <---l.1
return ans # <---l.2
if open < n:
brackets(ans, n,cur+"(",open+1,close)
if open > close:
brackets(ans, n,cur+")",open,close+1)
ans = []
ret = brackets(ans, 2, "", 0,0) # <---l.3
print(ans)
print(ret)
=====
return:
['(())', '()()']
None
I think I modify ans
list object on the line l.1 and return it, and on line l.2, I pass the ans
reference on line l.3.
But when I print both value ans
and ret
, ret
does not contain same value as ans
.
Of course, I just print ans
out for correct answer but I expected Python initialized variable ret
and assigned brackets
return reference to ret
on line l.3.
I got confused how python pass the reference through a function. Please let me know the relevant documents or the answer.