Python列表insert()
时间:2020-02-23 14:42:55 来源:igfitidea点击:
在本教程中,我们将看到关于Python List的insert方法。
Python列表插入方法用于将元素插入列表中指定的索引。
Python列表insert语法
list1.insert(index, element)
这里列表1是列表的对象。
list1.insert(1,'hello'):此代码将为第1次索引添加"hello"字符串。
请注意,Python索引从0开始,而不是1.
Python列表插入示例
我们可以简单地使用INSERT方法将元素添加到指定索引上的列表中。
让我们在简单的例子的帮助下了解这一点。
listOfItems=['Book','Table','TV'] listOfItems.insert(1,'Chair') print(listOfItems)
输出:
['Book', 'Chair', 'Table', 'TV']
我们可以通过输出看到的,"Table"字符串在第1索引处添加到Listofitems。
我们可以使用INSERT方法添加SET,COUPLE到列表.LET在示例的帮助下查看此。
listOfItems=['Book','Table','TV'] listOfItems.insert(2,('Car','Cycle')) print(listOfItems)
输出:
['Book', 'Table', ('Car', 'Cycle'), 'TV']