Python Remove List Elements: Easy Guide

You can use the del keyword or the remove() method to delete elements from a list.

Use the del keyword to remove elements at a specific index position.

my_list = [1, 2, 3, 4, 5]
del my_list[2]  # 删除索引为2的元素,列表变为 [1, 2, 4, 5]

Remove specified element using the remove() method.

my_list = [1, 2, 3, 4, 5]
my_list.remove(3)  # 删除元素3,列表变为 [1, 2, 4, 5]

Note: If the element you want to remove appears multiple times in the list, the remove() method will only remove the first matching element. To remove all matching elements, you can use a loop structure to achieve this.

bannerAds