增、
添加的方法:append;extend;insert
append:
用于在列表末尾添加新的对象。
#语法
list.append(obj) #obj 作为一个整体
#实例
list = [1,2,3]
list.append([4,5])
print(list)
>>>[1,2,3,[4,5]]
extend:
只接受一个列表作为参数, 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
#语法
list.extend(有序的字符序列/元素列表)
#实例
list = [1,2,3]
list.extend([6,7,8])
print(list)
>>>[1, 2, 3, 6, 7, 8]
insert:
插入到指定位置
list = [1,2,3]
list.insert(0,"哈哈") #下标"0"
print(list)
>>>
["哈哈", 1, 2, 3]
删、
删除的方法:del;pop;remove
del:
通过下标删除指定元素
#语法
list 列表名[下标索引]
#定义一个列表
list = [1,2,3]
del list[0]
print(list)
>>>
[2, 3]
del:第二种用法
提前杀死对象&提前杀死内存
>>>del list
pop:
属于了列表的方法,会从列表的后面开始删除
.pop()会有一个返回值,告知删除的元素
list = [1,2,3]
print(list.pop())
print(list)
>>>
3
[1, 2]
remove:
通过对象删除列表中的元素
定义一个列表
list = [1,2,3]
list.remove(1)
print(list)
>>>
[2, 3]
改、
列表名加上下标,附上想要的内容
# 定义一个列表
list = ["aa", 11, 3.14]
# 获取11
# value = list[1]
# print(value)
# 列表正
# 把list中的11 改成"hello"
# list[1] = "hello"
# print(list)
# 列表负
# 3.14改成3000
# list[-1] = 3000
# print(list)
查、
查找的方法:in;not in;index;count
# 定义一个列表
list = ["张三", "李四", "王五", "小明","小明"]
# 查找“张三”是否在列表中(in / not in)
# in
if "张三" in list:
print("存在列表中")
# not in
if "小华" not in list:
print("不存在列表中")
# 通过index 查看某一元素在列表中的下标索引
xb = list.index("张三")
print(xb)
# 通过count 查看某一元素在列表中出现的次数
c = list.count("小明")
print(c)