python中的insert函數(shù)怎么用

小億
102
2023-10-10 04:41:59
欄目: 編程語言

在Python中,insert函數(shù)用于在列表中的指定位置插入一個(gè)元素。語法如下:

list.insert(index, element)

其中,list是要操作的列表,index是要插入元素的位置,element是要插入的元素。

下面是一個(gè)使用insert函數(shù)的例子:

fruits = ['apple', 'banana', 'orange']
fruits.insert(1, 'grape')
print(fruits)

輸出結(jié)果為:

['apple', 'grape', 'banana', 'orange']

在這個(gè)例子中,fruits.insert(1, 'grape')'grape'插入到fruits列表的索引為1的位置,即'banana'之前。最終的結(jié)果是['apple', 'grape', 'banana', 'orange']。

0