gpt4 book ai didi

python - l1 是一个列表,l2 = l1;为什么 "l2 = l2 + [item]"不影响 l1 而 "l2 += [item]"呢?

转载 作者:行者123 更新时间:2023-11-28 21:26:13 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
What does plus equals (+=) do in Python?

我注意到一个奇怪的问题:

    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

输出是:

['2', '3']
['2', '3', '1']
['2', '3']

但是如果我将 l2 = l2 + [item] 更改为 l2 += [item],输出将是:

['2', '3']
['2', '3', '1']
['2', '3', '1']

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com