Python 中的 insert() 函数有助于将给定元素插入到列表的指定索引中。
list.insert(i, elem) #where element may be string, number, object etc.
insert() 函数接受两个参数。如果元素插入到指定索引处,则所有剩余元素都将向右移动。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| index | 要插入元素的索引 | 必需 |
| 元素 | 要插入到列表中的元素 | 必需 |
此方法不返回任何值。它通过向原始列表添加元素来修改原始列表。如果给定索引为零,则元素插入到第一个位置;如果索引为二,则元素插入到第二个元素之后,即其位置将是第三个位置。
# 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']
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]]