首页 > 解决方案 > 带列表的 for 循环

问题描述

编码

def f(x, l=[] ):
    for i in range(x):
        l.append(i*i)
        print(l)

f(2)
f(2, [3,2,1])
f(3)

程序结果:

[0]
[0, 1]
[3, 2, 1, 0]
[3, 2, 1, 0, 1]
[0, 1, 0]
[0, 1, 0, 1]
[0, 1, 0, 1, 4]

我不知道为什么 f(3) 打印:

[0, 1, 0]
[0, 1, 0, 1]
[0, 1, 0, 1, 4]

代替

[0]
[0, 1]
[0, 1, 4]

为什么f(2, [3,2,1])改变了f(3)的结果,但f(2)不干扰f(2, [3,2,1])

标签: pythonlistfor-loop

解决方案


推荐阅读