简体   繁体   English

Python输出以及为什么

[英]Python output and why

x = [10,20,30]

for i in x:
     print(i)
     x.append(40)
     x = [50,60]

print(x)

Output is : 输出为:

10
20
30
40
[50,60]

Why is 20, 30, 40 coming? 为什么20、30、40来? Not 50,60 不是50,60

The reason why this happens is because the loop uses the list object created in line 1. On line 5, you add 40 to this object, and then assign a new object to the x variable . 发生这种情况的原因是因为循环使用了在第1行中创建的列表对象 。在第5行中,将40添加到该对象,然后将新对象分配给x 变量 The loop is still using the object you created earlier. 循环仍在使用您之前创建的对象。

variable i is pointing to old x address. 变量i指向旧的x地址。 you append 40 in old address once. 您将40个旧地址附加一次。 the new x has different address which i is not pointing to. 新的x具有我未指向的其他地址。 variable i is still pointing to old x address. 变量i仍指向旧的x地址。

Extra: if you remember when we pass list to function , we pass it by address not as value. 另外:如果您还记得我们将列表传递给function时,我们通过地址而不是值来传递它。 this is same concept. 这是相同的概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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