共计 862 个字符,预计需要花费 3 分钟才能阅读完成。
Python 增加元素有三种办法:append、extend、insert
append:向列表增加元素,增加到尾部
实例:
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