列表的增加,删除知识点整理

列表的增加

增加方法操作描述
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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

被窝探险家104

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值