
2.3 列表
2.3.1 定义列表
列表使用一对方括号[ ]来定义。可以把列表当成普通的“数组”使用,但是列表中的元素可以是任意类型的:

列表的各个元素之间使用逗号进行分隔,alist列表中共有5个元素,前两个元素是整数,接下来的两个元素是字符串,最后一个元素是一个列表。
还可以通过list()工厂函数创建列表:

list()函数接收一个可迭代对象作为参数,将可迭代对象中的每一个元素都转换为列表的元素。字符串的元素是字符,所以第二个例子得到的列表中,每一项都是一个字符。
2.3.2 列表切片
与字符串类似,列表可以通过下标取出数据,也可以通过切片操作符取出一部分元素,用法完全一样。需要注意的是,通过下标取出的是单个元素,而通过切片得到的结果还是一个列表:

通过下标能够修改对应的值:

通过切片可以修改或增加多个值:

2.3.3 列表方法
➢ list.append()。
append()方法用于向列表中追加元素,也就是向列表尾部添加新的元素。这是追加元素必需的方法,采用不存在的下标进行赋值只会出错,而无法实现追加的目的。如下所示:


➢ list.insert()。
如果不是把元素追加到列表尾部,而是把它插入指定的位置,那么insert()方法就派上用场了。它可以接收两个参数:第一个参数指定插入位置的下标,第二个参数指定要插入的元素。如下所示:

➢ list.reverse()。
reverse()方法用于原地翻转列表:

➢ list.sort()。
sort()方法用于给列表排序。默认情况下采用的是升序排列,通过reversed=True能够实现降序排列。如下所示:


➢ list.pop()。
pop()方法用于弹出(删除并返回)一个元素,默认弹出最后一个元素,也可以弹出给定下标对应的元素。如下所示:

➢ list.remove()。
remove()方法用于在列表中通过值来删除一个给定的元素。如果该值出现了多次,则只会删除第一次出现的。如下所示:

➢ list.extend()。
extend()方法用于指向列表中追加的内容:


字符串“new”中的每一项是一个字母,共有三项,所以在extend的时候,就把每个字母都作为列表中的一项更新进去;而blist是一个列表,它有两项,每一项是一个字符串,所以在extend的时候,把这两个字符串作为两项更新到列表中了。
➢ list.index()。
index()方法用于获取元素第一次出现的下标:
