列表与变量的区别
变量可以存储一个元素,而列表是一个“大容器”可以存储N多个元素,程序可以方便地对这些数据进行整体操作。列表相当于其他语言中的数组
例:
a=10#变量存储的是一个对象的引用
print(id(a))
print(type(a))
print(a) #变量的id、类型、值
lst=['hello','world',98]
print(id(lst))
print(type(lst))
print(lst) #列表的id、类型、值
结果;
140704105957312
<class ‘int’>
10
3147505991808
<class ‘list’>
[‘hello’, ‘world’, 98]
列表的创建
列表需要使用中括号[],元素之间使用英文的逗号进行分隔
- 创建方式一:只使用中括号(其中lst只是变量名,可以随意命名)
lst=[’ ‘,’ ']
- 创建方式二:使用内置函数list()
- lst1=list([’ ‘,’ '])
例如:
a=['hello','world',98] #第一种创建方式
lst1=list(['hello','world',98])#第二种创建方式
print(a)
print(lst1)
结果:
[‘hello’, ‘world’, 98]
[‘hello’, ‘world’, 98]
列表的特点
- 列表元素按顺序有序排列
- 索引映射唯一数据
- 列表可以存储重复数据
- 任意数据类型混存
- 根据需要动态分配和回收内存
例:
lst=['hello','world',98]
print(lst)#列表元素按顺序有序排列
lst=['hello','world',98]
print(lst[0])#索引映射唯一数据,从前往后索引是从0开始。
print(lst[-1])#从后往前索引最后面的是-1,倒数第二个为-2,以此类推
lst=['hello','hello',98]#列表可以存储重复数据
print(lst)
结果:
[‘hello’, ‘world’, 98]
hello
98
[‘hello’, ‘hello’, 98]
其中索引映射唯一数据,从前往后索引是从0开始,从后往前是从-1开始,如图所示:
列表的查询操作
一、获取列表中指定元素的索引使用index()函数
index()函数:
- 如查找列表中存在N个相同元素,只返回相同元素的第一个索引的序列
例:
lst=['hello','world',98,'hello']
print(lst.index('hello'))
结果:
0
- 如果查找的元素在列表中不存在,则会抛出ValueError的错误提示
例:
lst=['hello','world',98,'hello']
print(lst.index('python'))
结果:
ValueError: ‘python’ is not in list
- 可以在指定的start和stop之间进行查找
例:
lst=['hello','world',98,'hello']
print(lst.index('hello',1,4))
结果:
3
注意:列表中索引的第一个元素是从0开始的
二、获取列表中的多个元素
语法格式:
列表名[start:stop:step]
切片操作(见图)
例:
lst=[10,20,30,40,50,60,70,80]
print(lst[1:6:1])
print(lst[::-1])#step为负数,逆序输出
print(lst[:-5:-2])#step为负数时,切片的最后一个元素默认为列表的第一个元素
结果:
[20, 30, 40, 50, 60]
[80, 70, 60, 50, 40, 30, 20, 10]
[80, 60]
判断指定元素在列表中是否存在,用in和not in
格式:
元素 in 列表名
元素 not in 列表名
例:
lst=[10,20,'python','hello']
print(10 in lst)
print(30 in lst)
print(30 not in lst)
print('python' in lst)
结果:
True
False
True
True
列表元素的遍历:
格式:
for 迭代变量 in 列表名:
操作
例:
lst=[10,20,'python','hello']
for item in lst:
print(item)
结果:
10
20
python
hello