当前位置: 首页 > 后端技术 > Python

python列表中如何添加元素

时间:2023-03-26 00:19:27 Python

Python有三种添加元素的方法:append、extend、insertappend:向列表中添加元素,添加到末尾示例:list=["my","name","is","mark","age",18]print("beforeadding:",list)list.append("test")print("afteradding:",list)printresult:beforeadding:['my','name','is','mark','age',18]添加后:['my','name','is','mark','age',18,'test']extend:addanotherlist将元素逐个添加到指定的list示例:list=["my","name","is","mark","age",18]print("beforeextend:",list)list2=["A","B"]list.extend(list2)print("afterextend:",list)打印结果:beforeextend:['my','name','is','mark','age',18After]extend:['my','name','is','mark','age',18,'A','B']inset(index,objectA):插入指定位置索引前面的对象objectA示例:list=["my","name","is","mark","age",18]print("beforeinsert:",list)list.insert(3,"test")print("Afterinsert:",list)打印结果:Beforeinsert:['my','name','is','mark','age',18]插入后:['my','name','is','test','mark','age',18]在python中将项目添加到列表如何在python中追加列表如何在python中对列表进行排序如何使用python列表插入方法python列出了你需要知道的一切