在 Python 中,列表允许我们将多个项目存储在一个变量中。例如,如果您需要存储班级所有学生的年龄,您可以使用列表来完成此任务。
列表类似于其他编程语言中的数组(动态数组,允许我们存储不同数据类型的项目)。
创建一个 Python 列表
我们通过将元素放在方括号 []
中,并用逗号分隔来创建列表。例如:
# a list of three elements
ages = [19, 26, 29]
print(ages)
输出
[19, 26, 29]
在这里,`ages` 列表有三个项目。
不同类型的列表项目
Python 列表非常灵活。我们还可以将不同数据类型的数据存储在一个列表中。例如:
# a list containing strings, numbers and another list
student = ['Jack', 32, 'Computer Science', [2, 4]]
print(student)
# an empty list
empty_list = []
print(empty_list)
列表特性
在 Python 中,列表是
- 有序的 - 它们维护元素的顺序。
- 可变的 - 创建后可以更改项目。
- 允许重复 - 它们可以包含重复的值。
访问列表元素
列表中的每个元素都关联着一个数字,称为索引。第一个项目的索引是 0,第二个项目的索引是 1,依此类推。

我们使用这些索引来访问列表的项目。例如:
languages = ['Python', 'Swift', 'C++']
# access the first element
print('languages[0] =', languages[0])
# access the third element
print('languages[2] =', languages[2])
输出
languages[0] = Python languages[2] = C++

负数索引
在 Python 中,列表也可以有负数索引。最后一个元素的索引是 -1,倒数第二个元素的索引是 -2,依此类推。

让我们看一个例子。
languages = ['Python', 'Swift', 'C++']
# access the last item
print('languages[-1] =', languages[-1])
# access the third last item
print('languages[-3] =', languages[-3])
输出
languages[-1] = C++ languages[-3] = Python
Python 中的列表切片
如果我们需要访问列表的一部分,我们可以使用切片运算符 :
。例如:
my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
print("my_list =", my_list)
# get a list with items from index 2 to index 4 (index 5 is not included)
print("my_list[2: 5] =", my_list[2: 5])
# get a list with items from index 2 to index -3 (index -2 is not included)
print("my_list[2: -2] =", my_list[2: -2])
# get a list with items from index 0 to index 2 (index 3 is not included)
print("my_list[0: 3] =", my_list[0: 3])
输出
my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm'] my_list[2: 5] = ['o', 'g', 'r'] my_list[2: -2] = ['o', 'g', 'r'] my_list[0: 3] = ['p', 'r', 'o']
切片时省略起始和结束索引
如果您省略起始索引,切片将从第一个元素开始。同样,如果您省略最后一个索引,切片将结束于最后一个元素。例如:
my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
print("my_list =", my_list)
# get a list with items from index 5 to last
print("my_list[5: ] =", my_list[5: ])
# get a list from the first item to index -5
print("my_list[: -4] =", my_list[: -4])
# omitting both start and end index
# get a list from start to end items
print("my_list[:] =", my_list[:])
输出
my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm'] my_list[5: ] = ['a', 'm'] my_list[: -4] = ['p', 'r', 'o'] my_list[:] = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
要了解更多关于切片的信息,请访问 Python 程序切片列表。
注意:如果指定的索引在列表中不存在,Python 会抛出 IndexError
异常。
向 Python 列表添加元素
如前所述,列表是可变的,我们可以更改列表中的项目。要将项目添加到列表的末尾,我们可以使用列表 append() 方法。例如:
fruits = ['apple', 'banana', 'orange']
print('Original List:', fruits)
fruits.append('cherry')
print('Updated List:', fruits)
输出
Original List: ['apple', 'banana', 'orange'] Updated List: ['apple', 'banana', 'orange', 'cherry']
在指定索引处添加元素
我们可以使用 insert() 方法在列表的指定索引处插入元素。例如:
fruits = ['apple', 'banana', 'orange']
print("Original List:", fruits)
fruits.insert(2, 'cherry')
print("Updated List:", fruits)
输出
Original List: ['apple', 'banana', 'orange'] Updated List: ['apple', 'banana', 'cherry', 'orange']
从其他可迭代对象向列表添加元素
列表 extend() 方法 将指定可迭代对象(如列表、元组、字典或字符串)的所有项目添加到列表的末尾。例如:
numbers = [1, 3, 5]
print('Numbers:', numbers)
even_numbers = [2, 4, 6]
print('Even numbers:', numbers)
# adding elements of one list to another
numbers.extend(even_numbers)
print('Updated Numbers:', numbers)
输出
Numbers: [1, 3, 5] Even numbers: [2, 4, 6] Updated Numbers: [1, 3, 5, 2, 4, 6]
更改列表项目
我们可以通过使用 =
运算符分配新值来更改列表中的项目。例如:
colors = ['Red', 'Black', 'Green']
print('Original List:', colors)
# change the first item to 'Purple'
colors[2] = 'Purple'
# change the third item to 'Blue'
colors[2] = 'Blue'
print('Updated List:', colors)
输出
Original List: ['Red', 'Black', 'Green'] Updated List: ['Purple', 'Black', 'Blue']
在这里,我们替换了
- 索引 0 处的元素为
'Purple'
- 索引 2 处的元素为
'Blue'
从列表中删除项目
我们可以使用 remove() 方法从列表中删除指定的项目。例如:
numbers = [2,4,7,9]
# remove 4 from the list
numbers.remove(4)
print(numbers)
输出
[2, 7, 9]
删除列表中的一个或多个元素
除了使用 remove()
方法,我们还可以使用 del 语句 从列表中删除项目。del
语句也可以用来删除多个元素甚至整个列表。
names = ['John', 'Eva', 'Laura', 'Nick', 'Jack']
# delete the item at index 1
del names[1]
print(names)
# delete items from index 1 to index 2
del names[1: 3]
print(names)
# delete the entire list
del names
# Error! List doesn't exist.
print(names)
输出
['John', 'Laura', 'Nick', 'Jack'] ['John', 'Jack'] Traceback (most recent call last): File "", line 15, in NameError: name 'names' is not defined
Python 列表长度
要查找列表中的元素数量(长度),我们可以使用内置的 len() 函数。例如:
cars = ['BMW', 'Mercedes', 'Tesla']
print('Total Elements:', len(cars))
输出
Total Elements: 3
遍历列表
我们可以使用 for 循环 遍历列表的元素。例如:
fruits = ['apple', 'banana', 'orange']
# iterate through the list
for fruit in fruits:
print(fruit)
输出
apple banana orange
Python 列表方法
Python 有许多有用的 列表方法,使处理列表变得非常容易。
方法 | 描述 |
---|---|
append() | 将项目添加到列表末尾 |
extend() | 将列表和其他可迭代对象的项目添加到列表末尾 |
insert() | 在指定索引处插入项目 |
remove() | 从列表中删除指定值 |
pop() | 返回并删除给定索引处的项目 |
clear() | 从列表中删除所有项目 |
index() | 返回第一个匹配项目的索引 |
count() | 返回列表中指定项目的计数 |
sort() | 按升序/降序对列表进行排序 |
reverse() | 反转列表中的项目 |
copy() | 返回列表的浅拷贝 |
另请阅读
- Python list() - 将其他数据类型转换为列表。
- Python 列表推导式 - 一种在一行中从另一个序列创建列表的简洁方式。
- Python enumerate() 函数 - 向列表添加计数器(默认为索引)。