一、列表
列表是Python中最基本的数据结构,是最常用的Python数据类型,列表的数据项不需要具有相同的类型
列表是一种有序的集合,可以随时添加和删除其中的元素
列表的索引从0开始
1、创建列表
>>> list1 = ['python', 2018, 'python3', 1994]
>>> list1
['python', 2018, 'python3', 1994]
>>> list2 = [1, 2, 3, 4]
>>> list2
[1, 2, 3, 4]
>>> list3 = ['a', 'b', 'c', 'd']
>>> list3
['a', 'b', 'c', 'd']
2、获取列表元素个数
>>> len(list1)
4
3、访问列表中的值
(1)使用索引来访问列表中的值,列表的索引从0开始:
>>> list1[0]
'python'
>>> list1[1]
2018
>>> list1[2]
'python3'
>>> list1[3]
1994
>>> list1[4]
Traceback (most recent call last):
File "", line 1, in
IndexError: list index out of range
注意:当索引超出范围时,Python会报一个IndexError错误,所以,要确保索引不要越界,记得最后一个元素的索引是len(list1) - 1。
(2)还可以获取列表最后一个元素:
>>> list1[-1]
1994
以此类推,可以获取倒数第2个、倒数第3个、倒数第4个:
>>> list1[-2]
'python3'
>>> list1[-3]
2018
>>> list1[-4]
'python'
>>> list1[-5]
Traceback (most recent call last):
File "", line 1, in
IndexError: list index out of range