Python 列表方法

Python list.insert() 方法用于在指定位置插入元素。

语法

lst.insert(index, element)

参数

index:插入位置。第二个参数 element:要插入的元素。

返回值

无返回值(返回 None)。原地修改列表。

示例

nums = [1, 2, 3]
nums.insert(0, 0)     # 头部插入
print(nums)           # [0, 1, 2, 3]

nums.insert(2, 99)    # 下标2处插入
print(nums)           # [0, 1, 99, 2, 3]

nums.insert(len(nums), 100)   # 末尾,等价 append
print(nums)           # [0, 1, 99, 2, 3, 100]

输出:

[0, 1, 2, 3]
[0, 1, 99, 2, 3]
[0, 1, 99, 2, 3, 100]

注意事项

index 超过末尾则插到末尾,负数 index 从右数位置插入。