一.了解什么事列表
在 Python 中,列表是一种序列类型的数据结构,用于存储一组有序的值。列表中的值可以是任何数据类型,包括数字、字符串、布尔值、对象等。列表是可变的,可随时添加、删除或修改其中的元素。列表使用方括号 [] 来定义,其中每个元素之间用逗号隔开。
二.列表创建
list()
lst = list([1,"chicken",[1,2]])
与
list = [1,"chicken",[1,2]]
三.访问列表的值
牵引访问
list()
lst = list([1,"chicken",[1,2]])
print(lst[0],lst[1])
2.切片访问
num = [1,2,3,4,5]
print(num[1:4])
list = [1,"chicken",[1,2,3],2,3]
print(list[1:4:2])
3.循环访问
list = [1,"apple",[1,2,3]]
for i in list:
print(i)
四.更新
1.牵引更新
list = ['chicken', 'black', 2022, 2023]
print(list[2])
list[2] = 2000
print(list[2])
添加
list1 = ['one','two', 'three']
list1.append('four')
print ("更新后的列表 : ", list1)
3.insret
list1 = ['one', 'two', 'three']
list1.insert(3,"four")
print (list1)
五.删除与清空
pop
list1 = ['one', 'two', 'three']
list1.pop(2)
print (list1)
2.del
list1 = ['one', 'two', 'three']
del list1[2]
print (list1)
3.remove
list1 = ['one', 'two', 'three']
list1.remove('three')
list1.remove(list1[2])
print (list1)
4.clear
list1 = ['one', 'two', 'three']
list1.clear()
print (list1)