
1.5.3 列表
列表(list)的元素有序但不唯一,且拥有索引。列表非常适合于元素需要有序存储且元素索引已知的场景。
列表和元组相似,唯一的区别是元组不可变,而列表中的元素可以移动,也可以增删。如果你确定一个集合中的元素不会被修改,请使用元组而非列表,因为操作元组比操作相同的列表更快。如果集合中的元素不可变,Python会进行一些优化。
创建Python列表,可以使用list函数:

或者使用字面量语法:

请注意,这里使用的是方括号([])。
使用len函数可以得到列表中元素的数量:

列表元素可以通过索引访问(第一个元素的索引为0):

我们还可以替换列表中的现有元素:

注意,不要使用列表中不存在的索引值,否则会弹出IndexError:

使用append方法可以将元素添加到列表的末尾:

通常,我们感兴趣的不仅是元素,还包括其索引。在这种情况下,我们可以使用enumerate函数,它会生成一个包含索引和元素的元组:

可以通过从其他列表中获取连续的元素来创建一个新的列表。这个过程被称为切片(slicing)。
列表切片
对列表进行切片操作,与使用方括号对列表进行索引类似,只不过我们使用的是两个用冒号分隔的索引:[<起始值>:<结束值>]。示例如下:

在上例中,我们有一个列表a:[1,2,3,4]。通过对该列表进行切片,选取从索引1(包含)到索引3(不包含)的元素,来创建一个新列表b。
注意:请记住,Python中的切片操作总是包含起始索引的元素,不包括结束索引的元素。
图1-4描绘了这个过程。

图1-4 对列表进行切片
切片操作符中的起始值和结束值都是可选的,因为它们有默认值。默认情况下,起始索引被赋值为列表中的第一个索引,也就是0。结束索引被赋值为列表中的最后一个索引加1,等于len(the_list)。

在这个例子中,列表b_1和b_2都是列表a的副本。之所以说是副本,是因为它们确实是不同的列表,你可以放心地修改b_1或b_2,而不会改变列表a。你可以通过执行以下操作来测试这一点:

另一个小技巧是使用负索引。负索引的计数方向是从列表末尾开始,并向列表开头移动。负索引可以用于切片,操作方式和正索引相同,只有一个小的区别:负索引从-1而非-0开始。例如,我们可以对一个列表切片,得到它最后的两个值,如下:

这里我们创建了一个新的列表,从列表的倒数第二个元素开始,一直到最后一个元素。图1-5描绘了这一点。
列表切片在Python中用途广泛。