my_list = ['hello', 666, True]
列表中的元素的类型不受限制,这点和数组不一样(也即是说列表里面还可以套个列表,be like:
my_list2 = [my_list, '123', 23, [1, 2, 3]]
my_list = [1, 2, 3, True, 'helloworld']
my_list2 = [my_list, 1]
print(my_list2)
# 打印:[[1, 2, 3, True, 'helloworld'], 1]
列表可以正向索引(第一个元素index为0)也可以反向索引(最后一个元素index为-1,向前以此递减1)
对于嵌套list,类似二维数组
列表的方法:
(为什么叫方法?:定义在类内的成员函数,就叫方法,list也是个类嘛,定义在list类内的一系列函数就叫方法
方法和函数功能一样,只是方法的使用格式不同
函数的使用:num = add(1,2)
方法的使用:student = Student()
num = student.add(1, 2)
list.append(元素) | |
list.extend(元素) | |
list.insert(下标,元素) | |
del list[下标] | |
list.pop(下标) | |
list.remove(元素) | |
list.clear() | |
list.count(元素) | |
list.index(元素) | |
len(列表) |
1. index查询:
my_list = [1, 2, 3, True, 'helloworld', True]
print(my_list.index(True))
# 打印:0
2.修改
my_list = [1, 2, 3, True, 'helloworld', True]
my_list[0] = 5
print(my_list)
# 打印:[5, 2, 3, True, 'helloworld', True]
3.insert插入
语法:列表.insert(下标,元素),在指定的下标位置,插入指定的元素
my_list = [1, 2, 3, True, 'helloworld', True]
my_list.insert(1, 5)
print(my_list)
# 打印:[1, 5, 2, 3, True, 'helloworld', True]
4.append追加,追加单个元素
在尾部追加,而不是指定位置
my_list = [1, 2, 3, True, 'helloworld', True]
my_list.append(7)
print(my_list)
# 打印:[1, 2, 3, True, 'helloworld', True, 7]
5.extend追加,追加一批
语法:列表.extend(其他数据容器),将其他数据容器的内容取出(不是物理意义上的“取出”哈,是一种复制),依次追加到列表尾部
my_list = [1, 2, 3, True, 'helloworld', True]
my_list2 = [4, 5, 6]
my_list.extend(my_list2)
print(my_list)
# 打印:[1, 2, 3, True, 'helloworld', True, 4, 5, 6]
6.删除
del:
my_list = [1, 2, 3, True, 'helloworld', True]
del my_list[2]
print(my_list)
# 打印:[1, 2, True, 'helloworld', True]
pop:
my_list = [1, 2, 3, True, 'helloworld', True]
element = my_list.pop(2)
# 可以拿个变量接收一下,本质上是把下标为2的元素取出来再返回
print(my_list)
# 打印:[1, 2, True, 'helloworld', True]
remove:删除某元素在列表中的第一个匹配项
语法:列表.remove(元素)
my_list = [1, 2, 3, True, 'helloworld', True]
my_list.remove(2)
print(my_list)
# 打印:[1, 3, True, 'helloworld', True]
7.clear清空
语法:列表.clear()
8.count统计某元素在列表内的数量
语法:列表.count(元素)
my_list = [1, 2, 3, True, 'helloworld', True]
element = my_list.count(True)
print(element)
# 打印:3
# 原来python认为1也是True啊!神奇
9.统计列表中全部的元素数量
语法:len(列表)
my_list = [1, 2, 3, True, 'helloworld', True]
count = len(my_list)
print(count)
# 打印:6