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]]