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 @   放氮气的蜗牛  阅读(244)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示