Given a list and we have to add an element at specified index in Python.
给定一个列表,我们必须在Python中的指定索引处添加一个元素。
list.appened() Method is used to append/add an element at the end of the list. But, if we want to add an element at specified index, we use insert() method. It takes 2 arguments, index and element.
list.appened()方法用于在列表末尾添加/添加元素。 但是,如果要在指定的索引处添加元素,则可以使用insert()方法。 它需要2个参数, index和element 。
Syntax:
句法:
list.insert(index, element)
Here,
这里,
list is the name of the list, in which we have to insert element at given index.
list是列表的名称,我们必须在其中给定index插入元素 。
index is the position, where we want to insert an element.
index是我们要插入元素的位置。
element is an element/item to be inserted in the list.
element是要在列表中插入的元素/项目。
Example:
例:
list.insert(2, 100)
It will insert 100 at 2nd position in the list name ‘list’.
Program:
程序:
# Declaring a list
list = [10, 20, 30]
# printing elements
print (list)
# O/P will be: [10, 20, 30]
# inserting "ABC" at 1st index
list.insert (1, "ABC")
# printing
print (list)
# O/P will be: [10, 'ABC', 20, 30]
# inserting "PQR" at 3rd index
list.insert (3, "PQR")
# printing
print (list)
# O/P will be: [10, 'ABC', 20, 'PQR', 30]
# inserting 'XYZ' at 5th index
list.insert (5, "XYZ")
print (list)
# O/P will be: [10, 'ABC', 20, 'PQR', 30, 'XYZ']
# inserting 99 at second last index
list.insert (len (list) -1, 99)
# printing
print (list)
# O/P will be: [10, 'ABC', 20, 'PQR', 30, 99, 'XYZ']
Output
输出量
[10, 20, 30]
[10, 'ABC', 20, 30]
[10, 'ABC', 20, 'PQR', 30]
[10, 'ABC', 20, 'PQR', 30, 'XYZ']
[10, 'ABC', 20, 'PQR', 30, 99, 'XYZ']
翻译自: https://www.includehelp.com/python/add-an-element-at-specified-index-in-a-list.aspx