Skip to content

Python 列表

Python 常用的内置容器包括 列表(list)元组(tuple)字典(dict)集合(set)。它们都可以存放多个元素,但语义不同:集合中的元素不重复;元组有序且不可变;字典保存键值对,键唯一;列表是有序、可变序列,可含重复元素,长度可随增删而改变,并支持用索引访问元素。

本教程介绍列表的常见用法与列表对象的主要方法。

列表的主要特点

  • 列表是可变序列
  • 用方括号 [] 创建,元素之间用逗号分隔,可嵌套列表。
  • 有序:保留元素插入顺序。
  • 支持非负索引负索引(从末尾向前计数)。
  • 可将元素解包到多个变量(与逗号分隔的写法配合使用)。
  • 允许重复元素,也允许空列表 []
  • 支持 +(拼接)与 *(重复)运算符。
  • 支持切片,由现有列表得到新列表。
  • 可用 for 循环遍历;用 in / not in 判断成员关系。
  • 常用于需要在原地增删改的同类型或混合类型数据序列。

创建列表

将元素放在方括号内,用逗号分隔:

python
fruits_list = ["Apple", "Banana", "Orange"]

列表中的元素类型可以不同:

python
random_list = [1, "A", object(), 10.55, True, (1, 2)]

嵌套列表示例:

python
nested_list = [1, [2, 3], [4, 5, 6], 7]

空列表:

python
empty_list = []

访问列表元素

索引从 0 开始:第 n 个元素使用索引 n - 1。例如访问第三个元素用索引 2

shell
>>> vowels_list = ["a", "e", "i", "o", "u"]
>>> vowels_list[0]
'a'
>>> vowels_list[4]
'u'

索引超出范围会抛出 IndexError

shell
>>> vowels_list[40]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

负索引

负索引从列表末尾往回数,合法范围为 -1-(len(list))

shell
>>> vowels_list = ["a", "e", "i", "o", "u"]
>>> vowels_list[-1]  # 最后一个
'u'
>>> vowels_list[-2]
'e'
>>> vowels_list[-5]
'a'

嵌套列表的索引

内层序列同样用 [行][列] 形式访问:

python
nested_list = [1, [2, 3], [4, 5, 6], 7]

print(nested_list[1][0])  # 2
print(nested_list[1][1])  # 3
print(nested_list[2][2])  # 6

若内层是元组等同样支持索引的序列,行为一致,例如 [1, (2, 3), (4, 5, 6), 7]

嵌套结构也支持负索引:

python
nested_list = [1, (2, 3), (4, 5, 6), 7]

print(nested_list[-3][0])
print(nested_list[-3][-1])
print(nested_list[-2][-1])

更新列表

对指定下标赋值即可修改元素:

shell
>>> my_list = [1, 2, 3]
>>> my_list[1] = 10
>>> my_list
[1, 10, 3]

遍历列表

使用 for 循环:

shell
>>> my_list = [1, 2, 3]
>>> for x in my_list:
...     print(x)
...
1
2
3

需要逆序遍历时,可使用 reversed()

shell
>>> my_list = [1, 2, 3]
>>> for x in reversed(my_list):
...     print(x)
...
3
2
1

更多循环写法见 循环

检查元素是否在列表中

使用 innot in

shell
>>> my_list = [1, 2, 3]
>>> 1 in my_list
True
>>> 10 in my_list
False
>>> 10 not in my_list
True
>>> 1 not in my_list
False

使用 del 删除元素或整个列表

del 可删除某个下标,或删除变量名本身(之后该名未再赋值则不存在):

shell
>>> my_list = [1, 2, 3]
>>> del my_list[1]
>>> my_list
[1, 3]
>>> del my_list
>>> my_list
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'my_list' is not defined

列表切片

切片用冒号分隔起止索引:左闭右开,即包含左侧索引,不包含右侧索引。

python
list_numbers = [1, 2, 3, 4, 5, 6, 7, 8]

print(list_numbers[1:3])   # [2, 3]
print(list_numbers[:4])    # 从头到索引 4 之前
print(list_numbers[5:])    # 从索引 5 到末尾
print(list_numbers[:-5])   # 负索引同样适用

列表连接(+)与重复(*

+ 生成新列表,将多个列表首尾相接:

shell
>>> l1 = [1]
>>> l2 = [2, 3]
>>> l3 = [4, "5", (6, 7)]
>>> l1 + l2 + l3
[1, 2, 3, 4, '5', (6, 7)]

* 将列表重复若干次:

shell
>>> l1 = [1, 2]
>>> l1 * 3
[1, 2, 1, 2, 1, 2]

运算符 中序列的 +* 语义一致。

列表长度与 list() 构造函数

len() 返回元素个数:

shell
>>> list_numbers = [1, 2, 3, 4]
>>> len(list_numbers)
4

内置函数 list() 可从任意可迭代对象构造列表,例如字符串、元组:

shell
>>> l1 = list("ABC")
>>> l1
['A', 'B', 'C']
>>> l1 = list((1, 2, 3))
>>> l1
[1, 2, 3]

列表对象常用方法

1. append(object)

在列表末尾添加一个元素:

shell
>>> list_numbers = [1, 2, 3, 4]
>>> list_numbers.append(5)
>>> print(list_numbers)
[1, 2, 3, 4, 5]

2. index(object, start, end)

返回对象第一次出现的下标;找不到则抛出 ValueErrorstartend 可选,用于限定搜索区间:

shell
>>> list_numbers = [1, 2, 1, 2, 1, 2]
>>> list_numbers.index(1)
0
>>> list_numbers.index(1, 1)
2
>>> list_numbers.index(1, 3, 10)
4
>>> list_numbers.index(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 10 is not in list

3. count(object)

统计元素出现次数:

shell
>>> list_numbers = [1, 2, 1, 2, 1, 2]
>>> list_numbers.count(2)
3
>>> list_numbers.count(1)
3

4. reverse()

原地反转列表:

shell
>>> list_numbers = [1, 2, 3]
>>> list_numbers.reverse()
>>> print(list_numbers)
[3, 2, 1]

5. clear()

清空列表:

shell
>>> list_numbers = [1, 2, 5]
>>> list_numbers.clear()
>>> print(list_numbers)
[]

6. copy()

返回浅拷贝(新列表对象,一层元素引用与原列表相同):

shell
>>> list_items = [1, 2, 3]
>>> tmp_list = list_items.copy()
>>> print(tmp_list)
[1, 2, 3]

7. extend(iterable)

将可迭代对象中的元素依次追加到列表末尾(常见来源:列表、元组、字符串等):

shell
>>> list_num = []
>>> list_num.extend([1, 2])
>>> print(list_num)
[1, 2]
>>> list_num.extend((3, 4))
>>> print(list_num)
[1, 2, 3, 4]
>>> list_num.extend("ABC")
>>> print(list_num)
[1, 2, 3, 4, 'A', 'B', 'C']

8. insert(index, object)

在指定下标之前插入。若 index 大于列表长度,则追加在末尾;若负索引越界到“左侧之外”,则插在开头。

shell
>>> my_list = [1, 2, 3]
>>> my_list.insert(1, "X")
>>> print(my_list)
[1, 'X', 2, 3]
>>> my_list.insert(100, "Y")
>>> print(my_list)
[1, 'X', 2, 3, 'Y']
>>> my_list.insert(-100, "Z")
>>> print(my_list)
['Z', 1, 'X', 2, 3, 'Y']
>>> my_list.insert(-2, "A")
>>> print(my_list)
['Z', 1, 'X', 2, 'A', 3, 'Y']

9. pop(index)

删除并返回指定下标处的元素;省略 index 时删除并返回最后一个元素。列表为空或下标越界时抛出 IndexError

shell
>>> my_list = [1, 2, 3, 4]
>>> my_list.pop()
4
>>> my_list
[1, 2, 3]
>>> my_list.pop(1)
2
>>> my_list
[1, 3]
>>> my_list.pop(-1)
3
>>> my_list
[1]
>>> my_list.pop(100)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range

10. remove(object)

删除第一个与参数相等的元素;不存在则抛出 ValueError

shell
>>> my_list = [1, 2, 3, 1, 2, 3]
>>> my_list.remove(2)
>>> my_list
[1, 3, 1, 2, 3]
>>> my_list.remove(20)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

11. sort(*, key=None, reverse=False)

原地排序。元素需可比较;key 指定排序依据(如 key=len);reverse=True 为降序。

shell
>>> list_num = [1, 0, 3, 4, -1, 5, 2]
>>> list_num.sort()
>>> list_num
[-1, 0, 1, 2, 3, 4, 5]
>>> list_num.sort(reverse=True)
>>> list_num
[5, 4, 3, 2, 1, 0, -1]

自定义排序键需元素支持相应比较或通过 key 函数产生可比较的值;与 函数 结合使用很常见。

列表与元组

  • 列表可变,元组不可变(详见 元组)。
  • 需要频繁增删改时,通常用列表存同构数据更合适。
  • 列表一般比元组占用更多内存(动态数组实现)。
  • 遍历列表与遍历元组性能差异在多数场景可忽略;选择时以是否需要修改为主。

小结

列表是 Python 中最常用的可变序列:有序、按索引访问、支持负索引与切片,并提供 appendextendinsertpopremovesort 等方法完成常见操作。任意可迭代对象都可用 list() 转为列表。

参考