def test(x,theList):
theList.append(x)
if x < 2:
x = x + 1
test(x,theList)
print x
print theList
test(1,[])
Why is the result [1,2]? And not only [1]?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because you execute the
printstatement after the recursive call totest()returns.Python objects are always passed by reference, so when the second invocation of test calls
theList.append(x), it is appending to the original list that was passed in, which is what you then print.