此 Python 函数可用于在用户指定的索引处将新项插入现有列表中。在本节中,我们将通过实际示例讨论如何使用此列表 insert 函数,其语法如下:
list.insert(New_item, index_position)
Python 列表 insert 函数示例
此方法帮助我们在给定的索引位置插入给定的项(New_item)或元素。下面的代码在索引位置 2 处添加了 50。
提示:请参阅 List 和 functions 文章,以全面了解 Python 中的相关内容。
a = [15, 20, 35, 90]
print("Original Items are : ", a)
a.insert(2, 50)
print("Items are : ", a)
Original Items are : [15, 20, 35, 90]
Items are : [15, 20, 50, 35, 90]
在此程序中,我们将三个值放入一个整数列表中。
a = [10, 20, 30, 40]
print("Original Items are : ", a)
a.insert(1, 70)
a.insert(3, 50)
a.insert(0, 120)
print("Items are : ", a)
Original Items are : [10, 20, 30, 40]
Items are : [120, 10, 70, 20, 50, 30, 40]
在此示例中,我们声明了一个单词字符串。接下来,我们使用此列表 insert 函数将元素放在给定的索引位置 1。
Fruits = ['Apple', 'Orange', 'Kiwi', 'Grape']
print("Original Elements are : ", Fruits)
Fruits.insert(1, 'Banana')
print("Elements are : ", Fruits)
Original Elements are : ['Apple', 'Orange', 'Kiwi', 'Grape']
Elements are : ['Apple', 'Banana', 'Orange', 'Kiwi', 'Grape']
此 程序 与第一个示例相同。但是,这次我们允许用户输入长度。接下来,我们使用 For Loop 来附加这些数量的元素。
intLi = []
number = int(input("Please enter the Total Number of Elements: "))
for i in range(1, number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
intLi.append(value)
print("Original Items are : ", intLi)
item = int(input("Please enter the New Item : " ))
position = int(input("Please enter the New Item : " ))
intLi.insert(position, item)
print("Final Items are : ", intLi)

这次,我们在嵌套列表中使用它,在给定的位置 2(索引)添加项。
MixLi = [[71, 222], [222, 13], [14, 15], [99, 77]]
print("Original Items are : ", MixLi)
MixLi.insert(2, [33, 55])
print("Items are : ", MixLi)
Original Items are : [[71, 222], [222, 13], [14, 15], [99, 77]]
Items are : [[71, 222], [222, 13], [33, 55], [14, 15], [99, 77]]
让我将此用于混合列表。
MiLi = ['apple', 1, 5, 'Kiwi', 'Mango']
print("Original Items are : ", MiLi)
MiLi.insert(2, 'Banana')
print("Items are : ", MiLi)
Original Items are : ['apple', 1, 5, 'Kiwi', 'Mango']
Items are : ['apple', 1, 'Banana', 5, 'Kiwi', 'Mango']