聚焦技术和人文,分享干货,共同成长。
append()
# 定义一个初始列表 fruits = ["apple", "banana", "cherry"] print("初始列表:", fruits) # 使用 append() 方法添加元素 fruits.append("date") print("使用 append() 添加元素后的列表:", fruits)
extend()
# 定义一个初始列表 fruits = ["apple", "banana", "cherry"] new_fruits = ["elderberry", "fig"] # 使用 extend() 方法添加元素 fruits.extend(new_fruits) print("使用 extend() 添加元素后的列表:", fruits)
insert()
# 定义一个初始列表 fruits = ["apple", "banana", "cherry"] # 使用 insert() 方法在索引 1 处插入元素 fruits.insert(1, "avocado") print("使用 insert() 添加元素后的列表:", fruits)
del
# 定义一个初始列表 fruits = ["apple", "banana", "cherry", "date"] print("初始列表:", fruits) # 使用 del 语句删除索引为 2 的元素 del fruits[2] print("使用 del 删除元素后的列表:", fruits)
remove()
# 定义一个初始列表 fruits = ["apple", "banana", "cherry", "banana"] # 使用 remove() 方法删除值为 "banana" 的第一个元素 fruits.remove("banana") print("使用 remove() 删除元素后的列表:", fruits)
pop()
# 定义一个初始列表 fruits = ["apple", "banana", "cherry"] # 使用 pop() 方法删除最后一个元素 last_fruit = fruits.pop() print("使用 pop() 删除的元素:", last_fruit) print("使用 pop() 删除元素后的列表:", fruits) # 使用 pop() 方法删除指定索引位置的元素 first_fruit = fruits.pop(0) print("使用 pop() 删除的元素:", first_fruit) print("再次使用 pop() 删除元素后的列表:", fruits)
# 定义一个初始列表 fruits = ["apple", "banana", "cherry"] print("初始列表:", fruits) # 修改索引为 1 的元素 fruits[1] = "blueberry" print("修改元素后的列表:", fruits)
posted on 2025-02-26 09:31 阿陶学长 阅读(88) 评论(0) 收藏 举报