列表 (list) 是 Python 的重要数据类型,可以通过往列表中添加新项目来扩充列表。如何往列表中添加新项目?Python 提供了多种方法,主要包括:append、extend、insert等。:
- append 方法
- extend 方法
- insert 方法
- 切片赋值方法
以上方法的使用示例如下所示。
# 定义一个列表 a_list = [3, 6, 9] # append 方法 a_list.append(12) # [3, 6, 9, 12] # extend 方法 a_list.extend([15]) # [3, 6, 9, 12, 15] # insert 方法 a_list.insert(len(a_list), 2) # [3, 6, 9, 12, 15, 2] # 切片赋值方法 a_list[len(a_list):] = [1] # [3, 6, 9, 12, 15, 2, 1]