为什么插入操作会将我的列表变为None类型?

2024-05-16 19:11:33 发布

您现在位置:Python中文网/ 问答频道 /正文

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
print(animals)

animals = animals.insert(2,"cobra")
print(animals) 

Insert函数将列表转换为None类型:

enter image description here

我不明白为什么会这样。在

来自python文档:

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list


Tags: ofthe函数atinsertprintanimalsduck
2条回答

insert函数不返回任何内容(或返回None,正如Cong Ma所注意到的):它修改输入列表!在

所以只需使用函数而不重新分配结果(无!)变量:

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
animals.insert(2,"cobra")
print(animals)
['aardvark', 'badger', 'cobra', 'duck', 'emu', 'fennec fox']

这是一个没有返回值的就地插入。用这个代替。在

animals.insert(2, "cobra")
print(animals) 

相关问题 更多 >