列表的增加
增加方法 | 操作描述 |
---|---|
append() | 在表的末尾添加一个元素 |
extend() | 在表的末尾至少添加一个元素 |
insert() | 在表的任意位置添加一个元素 |
切片 | 在列表的任意位置添加至少一个元素 |
- append()添加
#向列表的末尾添加一个元素
lst=[10,20,30,40]
print('添加元素之前',lst)
lst.append(100)
print('添加元素之后',lst)
lst2=['hello','world']
lst.append(lst2)#lst2做为一个元素添加到列表的末尾
print(lst)
输出结果:
添加元素之前[10,20,30,40]
添加元素之后[10,20,30,40,100]#这种创建不会改变id
[10,20,30,40,100,['hello','world']]
- extend()添加
#向列表的末尾一次添加多个元素
lst=[10,20,30,40]
print('添加元素之前',lst)
lst.append(100)
print('添加元素之后',lst)
lst2=['hello','world']
lst.extend(lst2)
print(lst)
输出结果:
添加元素之前[10,20,30,40]
添加元素之后[10,20,30,40,100]#这种创建不会改变id
[10,20,30,40,100,'hello','world']
- insert(index,x)添加
#在任意位置添加一个元素
lst=[10,20,30,40]
print('添加元素之前',lst)
lst.append(100)
print('添加元素之后',lst)
lst2=['hello','world']
lst.extend(lst2)
print(lst)
lst.insert(1,90)#在下标为1的地方添加元素90
print(lst)
输出结果:
添加元素之前[10,20,30,40]
添加元素之后[10,20,30,40,100]
[10,20,30,40,100,'hello','world']
[10,90,20,30,40,100,'hello','world']
- 切片
lst=[10,20,30,40]
print('添加元素之前',lst)
lst.append(100)
print('添加元素之后',lst)
lst2=['hello','world']
lst.extend(lst2)
print(lst)
lst.insert(1,90)
print(lst)
lst3=[True,False,'hello']
#在任意位置添加N多个元素
lst[1:]=lst3
print(lst)
输出结果:
添加元素之前[10,20,30,40]
添加元素之后[10,20,30,40,100]
[10,20,30,40,100,'hello','world']
[10,90,20,30,40,100,'hello','world']
[10,True,False,'hello']
删除
删除方法 | 操作描述 |
---|---|
一次删除一个元素 | |
remove() | 重复元素只删除第一个 |
元素不存在时抛出ValueError | |
删除一个指定索引位置的元素 | |
pop() | 指定索引不存在时抛出IndexError |
不指定索引,删除列表中最后一个元素 | |
切片 | 一次至少上出一个元素 |
clear() | 清空列表 |
del | 删除列表 |
remove():
lst=[10,20,30,40,50,60,70,30]
lst.remove(30)#从列表中删除一个元素,如果有重复元素只删除第一个
print(lst)
lst.remove(100)#ValueError: list.remove(x): x not in list
pop():
#pop()根据索引移除元素
lst.pop(1)
print(lst)
lst.pop(9)#此时会出现报错IndexError: pop index out of range
lst.pop()
print(lst)#如果不指定参数索引,将删除列表最后一个元素
切片:
new_list=list[1:3]
print('原列表',lst)
print('切片后的列表',new_list)
lst[1:3]=[]
print(lst)#不产生新的列表对象,而是删除原列表的内容
clear():清除列表中所有元素
lst.clear()
print(lst)
输出结果:[ ]
del():将语句中的列表对象删除
del lst
print(lst)#NameError: name 'lst' is not defined.