python列表添加元素之append()函数和insert()函数

append()函数

在列表中添加新元素时,最简单的方法就是附加在末尾:

list_1 = ['one', 'two', 'three']
print(list_1)

list_1.append('four')
print(list_1)

函数append()就是将'four'添加在列表末尾,而且不影响列表其他元素

['one', 'two', 'three']
['one', 'two', 'three', 'four']

insert()函数

insert()函数顾名思义"插入",可以在列表任何位置插入元素,

insert(索引,元素),列表里元素的索引(位置)和C语言一样是从0开始的

list_1 = ['one', 'two', 'three']
list_1.insert(3, 'four')
print(list_1)
['one', 'two', 'three', 'four']

如果该位置上已经有元素了,那么该元素以及后面的元素会右移一位,如:  

list_1 = ['one', 'two', 'three']
list_1.insert(1, 'four')
print(list_1)
['one', 'four', 'two', 'three']

本来'two'元素在列表list_1索引1的位置,但是'four'插入到了1的位置,那么'two'以及后面的'three'就会右移一位

posted @ 2023-05-14 00:49  放氮气的蜗牛  阅读(121)  评论(0编辑  收藏  举报  来源