Python list insert描述
Python list insert()方法可以将元素插入到列表的任意位置。可以通过偏移量来告诉insert()方法你要插入的位置,insert方法会将元素插入到该索引对应元素的前面。
语法和参数
list.insert(index, element)
名称 含义 备注
index 要插入的位置索引 不可省略的整型参数
element 要插入的元素 不可省略的参数
返回值
None。即list.insert()方法没有返回值,其作用于list本身。
使用示例
插入到指定位置前
insert()方法是将元素插入到索引对应元素的前面。例如对应list:
a b c 12 qwe 233
现调用list.insert(3, d),则insert()方法将元素d 插入到第三个索引对应的元素12之前,即:
a b c d 12 qwe 233
代码演示:
demo = [“a”, “b”, “c”, 12, “qwe”, 233]
demo.insert(3, “d”)
demo
[‘a’, ‘b’, ‘c’, ‘d’, 12, ‘qwe’, 233]
但是不要理解为将元素插入到指定的索引上。比如当index参数为负数时:
demo = [1, 2, 3]
demo.insert(-1, 4)
demo
[1, 2, 4, 3]
insert方法将元素4插入到了列表倒数第1个索引对应元素3的前面,而不是将元素4插入到索引值为-1的位置上。
注意事项
插入的索引超出列表长度范围
当索引值超出了列表长度的有效范围,insert()方法不会抛出异常,而是将元素插入到列表的两端:如果索引值为正整数,则将元素插入到列表尾部,这种情况下insert()方法与append()方法效果相同;如果索引值为负整数,则将元素插入到列表头部。
demo = [“Python”, “C”]
demo.insert(2, “Java”)
demo
[‘Python’, ‘C’, ‘Java’]
demo.insert(-4, “HTML”)
demo
[‘HTML’, ‘Python’, ‘C’, ‘Java’]
索引值不是整数
当插入的索引值不是整数时,insert()方法抛出TypeError异常。
demo.insert(3.3, “MySQL”)
Traceback (most recent call last):
File “”, line 1, in
TypeError: integer argument expected, got float