l1 is a list, l2 = l1; why doesn't “l2 = l2 + [item]” affect l1 while “l2 += [item]” does?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
What does plus equals (+=) do in Python?
我注意到一个奇怪的问题:
1 2 3 4 5 6 7 8 9 10 11 | l1 = ['1', '2', '3'] l2 = l1 item = l2.pop(0) # the pop operation will effect l1 print l1 l2 = l2 + [item] # why"l2 = l2 + [item]" does't effect l1 while"l2 += [item]" does. print l2 print l1 |
输出是:
1 2 3 | ['2', '3'] ['2', '3', '1'] ['2', '3'] |
但如果我把
1 2 3 | ['2', '3'] ['2', '3', '1'] ['2', '3', '1'] |
对于数字,两者都是相同的,因为它们是不可变的,因此不能用
由于
分配
代码执行的交互式可视化:
- 弗斯特
- 第二
一些相关链接:
用python命名。
更多关于列表