Python列表是一种有序的集合,可以随时添加和删除其中的元素。以下是一些常用的列表操作:
添加元素:
- 使用
append()方法在列表末尾添加一个元素:list.append(item) - 使用
insert()方法在指定位置插入一个元素:list.insert(index, item) - 使用
extend()方法将另一个列表的元素添加到当前列表:list.extend(another_list)
- 使用
删除元素:
- 使用
remove()方法删除列表中第一个匹配的元素:list.remove(item) - 使用
pop()方法删除并返回指定位置的元素:list.pop(index) - 使用
del关键字删除指定位置的元素:del list[index] - 使用
clear()方法清空列表:list.clear()
- 使用
获取元素:
- 使用索引访问列表中的元素:
list[index] - 使用
count()方法统计某个元素在列表中出现的次数:list.count(item) - 使用
index()方法获取某个元素在列表中首次出现的索引:list.index(item) - 使用
reverse()方法反转列表:list.reverse() - 使用
sort()方法对列表进行排序:list.sort()(默认升序)或list.sort(reverse=True)(降序)
- 使用索引访问列表中的元素:
示例代码:
# 创建一个列表
my_list = [1, 2, 3, 4, 5]
# 添加元素
my_list.append(6) # [1, 2, 3, 4, 5, 6]
my_list.insert(0, 0) # [0, 1, 2, 3, 4, 5, 6]
my_list.extend([7, 8]) # [0, 1, 2, 3, 4, 5, 6, 7, 8]
# 删除元素
my_list.remove(0) # [1, 2, 3, 4, 5, 6, 7, 8]
my_list.pop(0) # [2, 3, 4, 5, 6, 7, 8]
del my_list[0] # [3, 4, 5, 6, 7, 8]
my_list.clear() # []
# 获取元素
print(my_list[0]) # IndexError: list index out of range
print(my_list.count(3)) # 1
print(my_list.index(4)) # 1
my_list.reverse() # [8, 7, 6, 5, 4, 3]
my_list.sort() # [3, 4, 5, 6, 7, 8]