
2.2.2 列表的基本操作与方法

2-2 列表的基本操作与方法
1.通用操作
作为序列的一员,列表可使用“+”和“*”操作符,前者用于组合列表,后者用于重复列表。
与列表相关的函数有:①len()返回列表元素个数;②max()返回列表元素最大值;③min()返回列表元素最小值。
【例2-9】 操作符、函数在列表表达式或语句中的使用。

运算结果:

2.删除列表
对于已经创建的列表,如果不再使用,可以使用del关键字将其删除。
del关键字的语法格式为:

其中,listname表示要删除列表的名称。
【例2-10】 删除列表。

运算结果:

在实际开发中并不经常使用del来删除列表,因为Python自带的垃圾回收机制会自动销毁无用的列表,即使开发者不手动删除,Python也会自动将其回收。
3.append()方法添加元素
append()方法用于在列表的末尾追加元素,该方法的语法格式如下:

其中,listname表示要添加元素的列表;obj表示要添加到列表末尾的数据,它可以是单个元素,也可以是列表、元组等。
【例2-11】 用append()方法添加元素。

运算结果:

从本例可以看出,当给append()方法传递列表或者元组时,此方法会将它们视为一个整体,作为一个元素添加到列表中,从而形成包含列表和元组的新列表。
4.extend()方法添加元素
extend()和append()的不同之处在于:extend()不会把列表或者元组视为一个整体,而是把它们包含的元素逐个添加到列表中。
extend()方法的语法格式如下:

其中,listname指的是要添加元素的列表;obj表示要添加到列表末尾的数据,它可以是单个元素,也可以是列表、元组等。
【例2-12】 用extend()方法添加元素。

运算结果:

5.insert()方法插入元素
append()和extend()方法只能在列表末尾插入元素,如果希望在列表中间某个位置插入元素,那么可以使用insert()方法。
insert()的语法格式如下:

其中,index表示指定位置的索引值。insert()会将obj插入到listname列表第index个元素的位置。
当插入列表或者元组时,insert()也会将它们视为一个整体,作为一个元素插入到列表中,这一点和append()是一样的。
【例2-13】 用insert()方法插入元素。


运算结果:

6.del删除元素
del是Python中的关键字,专门用来执行删除操作,它不仅可以删除整个列表,还可以删除列表中的某些元素。
del可以删除列表中的单个元素,格式为:

其中,listname表示列表名称,index表示元素的索引值。
del也可以删除中间一段连续的元素,格式为:

其中,start表示起始索引,end表示结束索引。del会删除从索引start到end之间的元素,不包括end位置的元素。
【例2-14】 使用del删除单个列表元素。

运算结果:

【例2-15】 使用del删除一段连续的元素。


运算结果:

7.pop()删除元素
用pop()方法删除列表中指定索引处的元素,具体格式如下:

其中,listname表示列表名称,index表示索引值。如果不写index参数,默认会删除列表中的最后一个元素,类似于数据结构中的“出栈”操作。
至于数据结构中的“入栈”操作,Python并没有提供相应的push()方法,这时可以使用append()来代替。
【例2-16】 根据索引值删除元素。

运算结果:

8.remove()删除
除了del关键字,Python列表还提供了remove()方法,该方法会根据元素本身的值来进行删除操作。需要注意的是,remove()方法只会删除第一个和指定值相同的元素,而且必须保证该元素是存在的,否则会引发ValueError错误。
【例2-17】 根据索引值删除元素。


运算结果:

9.clear()删除列表所有元素
clear()用来删除列表的所有元素,即清空列表。
【例2-18】 清空列表。

运算结果:

10.列表修改元素
有两种修改列表(list)元素的方法,可以每次修改单个元素,也可以每次修改一组元素(多个)。
(1)修改单个元素
修改单个元素非常简单,直接对元素赋值即可。
【例2-19】 修改列表的单个元素。

运算结果:

使用索引得到列表元素后,通过“=”赋值就改变了元素的值。
(2)修改一组元素
Python支持通过切片语法给一组元素赋值。在进行这种操作时,如果不指定步长(step参数),Python就不要求新赋值的元素个数与原来的元素个数相同;这意味着该操作既可以为列表添加元素,也可以为列表删除元素。
【例2-20】 修改列表的一组元素。

运算结果:

【例2-21】 使用字符串赋值时自动把字符串转换成每个字符都是一个元素的序列。

运算结果:

【例2-22】 使用切片语法时指定步长(step参数)。

运算结果:

本例中,使用切片语法指定步长时,要求所赋值的新元素个数与原有元素的个数相同。
11.count()方法
count()方法用来统计某个元素在列表中出现的次数,基本语法格式为:

其中,listname代表列表名,obj表示要统计的元素。
如果count()返回0,表示列表中不存在该元素,所以count()也可以用来判断列表中的某个元素是否存在。
【例2-23】 count()方法用于统计元素个数和判断元素存在与否。


运算结果:

12.index()方法
index()方法用来查找某个元素在列表中出现的位置(也就是索引),如果该元素不存在,则会导致ValueError错误,所以在查找之前最好使用count()方法判断一下。
index()的语法格式为:

其中,listname表示列表名称,obj表示要查找的元素,start表示起始位置,end表示结束位置。
start和end参数用来指定检索范围。
start和end可以都不写,此时会检索整个列表。
如果只写start不写end,那么表示检索从start到末尾的元素。
如果start和end都写,那么表示检索start和end之间的元素。
index()方法会返回元素所在列表中的索引值。
【例2-24】 返回元素所在列表中的索引值。

运算结果:
