列表(list)
列表是一种有序的序列结构,用 [] 定义,数据之间使用“,”分隔,是使用最频繁的数据类型。
(1)空列表,就是一个不包含任何元素的空列表。
list_a = []
(2)列表中可包含不同的数据类型。
list_b = [1,2,"test",3]
(3)列表中数据可重复。
list_c = [1,2,3,2,1]
(4)列表中可包含列表。
list_d = [1,2,3,["test","product"],4,5]
一、使用索引获取列表元素
列表中第一个元素索引是从0开始的,可以通过列表[索引]从列表中取值。
list_d = [1,2,3,["test","product"],4,5]
# 获取列表第一个元素
print(list_d[0])
# 获取列表第二个元素
print(list_d[1])
通过倒序的方式获取列表末尾值,从-1开始。
list_d = [1,2,3,["test","product"],4,5]
# 获取列表最后一个元素
print(list_d[-1])
# 获取列表倒数第二个元素
print(list_d[-2])
# 获取列表倒数第三个元素
print(list_d[-3])
值得注意的是print(list_d[-3]) 取出的值是['test', 'product']。
通过索引的方式进行列表取值时,索引值不能超出范围,否则会报IndexError:list index out of range错误。
list_d = [1,2,3,["test","product"],4,5]
# 列表一共有6个值,下标为0至5,所以list_d[6]取值失败
print(list_d[6])
上面是通过索引取具体某个值的方法,还有一种是通过切片方式取