python 中的insert()函数有助于将给定元素插入到列表的指定索引中。
 **list.insert(i, elem)** #where element may be string, number, object etc. 
插入()参数:
insert()函数接受两个参数。如果元素被插入到指定的索引中,所有剩余的元素都会向右移动。
| 参数 | 描述 | 必需/可选 | 
|---|---|---|
| 指数 | 需要插入元素的索引 | 需要 | 
| 元素 | 要插入列表的元素 | 需要 | 
插入()返回值
这个方法不返回值。它通过添加元素来修改原始列表。如果给定的索引为零,元素将插入到第一个位置,如果索引为二,元素将插入到第二个元素之后,即第三个位置。
Python 中insert()方法的示例
示例 1:如何将元素插入列表
 # 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'] 示例 2:如何将元组作为元素插入列表
 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]] 原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/254999.html
 
 微信扫一扫
微信扫一扫  支付宝扫一扫
支付宝扫一扫 