在Python中,`insert()`函数用于在列表(list)的指定位置插入一个元素。以下是`insert()`函数的基本用法:
```python
list.insert(index, element)
其中:
`index` 是要插入元素的位置(从0开始计数)。
`element` 是要插入到列表中的元素。
`insert()`函数会将元素插入到指定位置,并将该位置原有的元素及其后的元素依次往后移动。
示例:
```python
插入单个元素
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, 'orange')
print(fruits) 输出:['apple', 'orange', 'banana', 'cherry']
插入多个元素
numbers = [1, 2, 3, 4, 5]
numbers.insert(2, 10, 11, 12)
print(numbers) 输出:[1, 2, 10, 11, 12, 3, 4, 5]
插入可迭代对象(如元组)
mixed_list = [{1, 2}, [5, 6, 7]]
number_tuple = (3, 4)
mixed_list.insert(1, number_tuple)
print(mixed_list) 输出:[{1, 2}, (3, 4), [5, 6, 7]]
请注意,Python中的索引从0开始,所以`index=0`表示列表的第一个位置,`index=1`表示第二个位置,以此类推。