一:在列表末尾添加元素

list = ["python", "hello"]
list.append("world")
print(list)

# 结果 ["python", "hello", "world"]

二:在列表中插入元素

list = ["python", "hello"]
list.insert(0, "world")
print(list)

# 结果 ["world", "python", "hello"]

三:从列表中删除元素

1.del语句删除

list = ["python", "hello"]
del list[0]
print(list)

# 结果 ["hello"]

2.使用pop()方法删除

list = ["python", "hello"]
hasDel = list.pop()
print(list)
print(hasDel)

# 结果 ["python"]
# 结果 hello

pop()方法会删除列表尾的元素,并可以返回被删除的值。

pop()方法实际上可以删除任意位置的元素,只是默认删除尾部而已。

如:pop(0) 即可删除第一个元素。

总结 :如果只是删除元素,用del,如果被删除的元素需要用到,用pop()。

3.根据值删除元素

list = ["python", "hello"]
list.remove("hello")
print(list)

# 结果 ["python"]

remove()方法默认删除列表中第一个出现的元素,如果删除全部,循环删除即可。