insert()
方法在指定索引处将元素插入到列表中。
示例
# create a list of vowels
vowel = ['a', 'e', 'i', 'u']
# 'o' is inserted at index 3 (4th position)
vowel.insert(3, 'o')
print('List:', vowel)
# Output: List: ['a', 'e', 'i', 'o', 'u']
列表 insert() 的语法
insert()
方法的语法是
list.insert(i, elem)
在这里,elem 被插入到列表的第 i 个索引处。所有在 elem
之后的元素都向右移动。
insert() 参数
insert()
方法接受两个参数
- index - 元素需要插入的索引
- element - 这是要插入到列表中的元素
注意事项
- 如果 index 为 0,则元素将插入到列表的开头。
- 如果 index 为 3,则插入元素的索引将为 3(列表中的第 4 个元素)。
insert() 的返回值
insert()
方法不返回任何内容;返回 None
。它只更新当前列表。
示例 1:将元素插入到列表中
# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]
# insert 11 at index 4
prime_numbers.insert(4, 11)
print('List:', prime_numbers)
输出
List: [2, 3, 5, 7, 11]
示例 2:将元组(作为元素)插入到列表中
mixed_list = [{1, 2}, [5, 6, 7]]
# number tuple
number_tuple = (3, 4)
# inserting a tuple to the list
mixed_list.insert(1, number_tuple)
print('Updated List:', mixed_list)
输出
Updated List: [{1, 2}, (3, 4), [5, 6, 7]]
另请阅读