Tutorial Study Image

Python insert()

Python 中的 insert() 函数有助于将给定元素插入到列表的指定索引中。


list.insert(i, elem) #where element may be string, number, object etc.
 

insert() 参数

insert() 函数接受两个参数。如果元素插入到指定索引处,则所有剩余元素都将向右移动。

参数 描述 必需/可选
index 要插入元素的索引 必需
元素 要插入到列表中的元素 必需

insert() 返回值

此方法不返回任何值。它通过向原始列表添加元素来修改原始列表。如果给定索引为零,则元素插入到第一个位置;如果索引为二,则元素插入到第二个元素之后,即其位置将是第三个位置。

Python 中 insert() 方法的示例

示例 1:如何向列表中插入元素


# alphabets list
alphabets = ['a', 'b', 'd', 'e']

# 'c' is inserted at index 2
# the position of 'c' will be 3rd
vowel.insert(2, 'c')

print('Updated List:', alphabets)
 

输出


Updated List: ['a', 'b', 'c', 'd', 'e']

示例 2:如何将元组作为元素插入到列表中


firs_list = [{1, 2}, [5, 6, 7]]

# ex tuple
ex_tuple = (3, 4)

# inserting a tuple to the list
firs_list.insert(1, ex_tuple)

print('Final List:', firs_list)
 

输出


Final List: [{1, 2}, (3, 4), [5, 6, 7]]