为什么将它保留在列表中?

时间:2012-11-18 22:50:25

标签: python

def test(x,theList): 
    theList.append(x) 
    if x < 2: 
        x = x + 1 
        test(x,theList) 
        print x 
        print theList 

test(1,[]) 

为什么结果[1,2]?不仅仅是[1]?

2 个答案:

答案 0 :(得分:2)

因为在递归调用print之后执行test()语句。

Python对象总是通过引用传递,所以当第二次调用测试调用theList.append(x)时,它会附加到传入的原始列表中,然后打印出来。

答案 1 :(得分:0)

def test(x,theList): 
    if x < 2: 
        theList.append(x) 
        x = x + 1 
        test(x,theList) 
        print x 
        print theList 

test(1,[])