列表:列表是python中最常用的数据类型,列表中的数据不需要具有相同的数据类型,它是一个有序的序列
1.列表的创建
空列表的创建:
>>> li = []
>>> print(type(li))
<class 'list'>
>>> li1 = list()
>>> print(type(li1))
<class 'list'>
注意: 用此方式创建的空列表,长度为0,初始化时不能直接通过下标赋值,
即:li[0] = 'test',只能通过append()或extend()添加元素
创建并初始化列表:
此列表可以在索引范围内对列表元素进行赋值,但是超过索引即给列表中添加新的元素需要使用append()或extend()
li = [None] * 5
li1 = ['hello', 'python', 'hello']
# 列表里也可以嵌套列表
>>> list2 = [1,2,3,4,[1,1.2,True,'python']]
>>> print(list2, type(list2))
[1, 2, 3, 4, [1, 1.2, True, 'python']] <class 'list'>
>>> print(list2[-1])
[1, 1.2, True, 'python']
2.列表的特性
1.索引
>>> service = ['http','ftp','ssh']
正向索引
>>> print(service[0])
>>> print(service[0])
http
反向索引
>>> print(service[-1])
ssh
2.切片
>>> print(service[::-1])
['ssh', 'ftp', 'http']
>>> print(service[1:])
['ftp', 'ssh']