幽沉谢世事,俯默窥唐虞。这篇文章主要讲述Python 列表如何添加元素相关的知识,希望能为你提供帮助。
python添加元素有三种方法:append、extend、insert
append:向列表添加元素,添加到尾部
实例:
【Python 列表如何添加元素】list=["
my"
,"
name"
,"
is"
,"
mark"
,"
age"
,18]
print("
添加前:"
,list)
list.append("
test"
)
print("
添加后:"
,list)
打印结果:
添加前: [my, name, is, mark, age, 18]
添加后: [my, name, is, mark, age, 18, test]
extend:将另外一个列表的元素逐一添加到指定列表中
实例:
list=["
my"
,"
name"
,"
is"
,"
mark"
,"
age"
,18]
print("
extend前:"
,list)
list2=["
A"
,"
B"
]
list.extend(list2)
print("
extend后:"
,list)
打印结果:
extend前: [my, name, is, mark, age, 18]
extend后: [my, name, is, mark, age, 18, A, B]
inset(index,objectA):在指定位置index前面插入对象objectA
实例:
list=["
my"
,"
name"
,"
is"
,"
mark"
,"
age"
,18]
print("
insert前:"
,list)
list.insert(3,"
test"
)
print("
insert后:"
,list)
打印结果:
insert前: [my, name, is, mark, age, 18]
insert后: [my, name, is, test, mark, age, 18]
add items to a list in python
how to append list in python
how to sort list in python
how to use python list insert method
python lists everything you need to know
推荐阅读
- go语言--语言常量
- Web架构单机房多机房公有云私有云
- #私藏项目实操分享#Spring Boot Serverless 实战 | 性能调优
- Linux 常用基本命令总结
- #yyds干货盘点#SSH远程连接介绍
- #yyds干货盘点# C#中的类继承
- 当C++中对派生类方法给予更严格的访问时会发生什么?
- 什么是C++中的数组衰减(如何预防?)
- 机器学习中的AutoML是什么()