为什么输出L2、L3时,后面插入的字符串还是重复插入,明明设置不是一个队列内?

来源:5-5 Python向list添加新的元素

慕标2526337

2024-02-26 13:39

# Enter a code

L=['Alice','Bob','Candy','David','Ellena']

L1 = L

L1.append('Gen')

L2 = L


L1.append('Phoebe')

L1.append('Zero')

print(L1)


L2.append('Zero')

L2.insert(6,'Phoebe')

print(L2)

L3=['Gen','Phoebe','Zero']

print(L+L3)


写回答 关注

1回答

  • 执剑人程心
    2024-02-26 23:42:11
    因为两者指向同一个列表对象,如:

    list = [1, 2, 3]

    list1 = list
    list1.append(4)
    print('list1', list1)
    print('list', list)

    list1 [1, 2, 3, 4]
    list [1, 2, 3, 4]


    要避免这种情况,使用copy,如:
    list2 = list.copy()
    print('list2', list2)
    list2.append(100)
    print('list2', list2)
    print('list', list)

    list2 [1, 2, 3, 4]
    list2 [1, 2, 3, 4, 100]
    list [1, 2, 3, 4]

Python3 入门教程

python3入门教程,让你快速入门并能编写简单的Python程序

164438 学习 · 1134 问题

查看课程

相似问题