# 在 Python 中的列表中刪除多個元素

## 使用 `if...else` 控制語句從列表中刪除多個元素

``````list1 = [1,2,3,4,5,6,7,8,9,10,20]
print("Original list : ",list1)

for ele in list1:
if (ele%2) != 0:
list1.remove(ele)

print("List after deleting all values which are odd : ",list1)
``````

``````Original list :  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20]
List after removing all the odd values :  [2, 4, 6, 8, 10, 20]
``````

## 使用 Python 中的列表推導方法從列表中刪除多個元素

``````l1 = [2,3,4,5,6,7,8,9,10,20,80,99]
l2 = [ x for x in l1 if x%2==0 ]

print("Original list : ",l1)
print("List after deleting all the odd values present in List : ",l2)
``````

``````Original List :  [2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 80, 99]
List after deleting all the odd values present in List :  [2, 4, 6, 8, 10, 20, 80]
``````

## 使用列表切片從列表中刪除多個元素

``````l1 = [2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 80, 99]
print("Original list : ",l1)

del l1[2:5]

print("List after removing values at index 2, 3 and 4 : ",l1)
``````

``````Original List :  [2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 80, 99]
List after removing values at index 2, 3 and 4 :  [1, 2, 6, 7, 8, 9, 10, 20, 80, 99]
``````

## 使用 `for` 迴圈從列表中刪除多個元素

``````l1 = [2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 80, 99]
print("Original list : ",l1)

indexes_to_be_removed = [0, 2, 5]

for idx in sorted(indexes_to_be_removed, reverse = True):
del l1[idx]

print("List after removing values at index 0, 2 and 5: ",l1)
``````

``````Original List :  [2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 80, 99]
List after removing values at index 0, 2 and 5:  [3, 5, 6, 8, 9, 10, 20, 80, 99]
``````

## 相關文章 - Python List

• Python 列表方法 append 和 extend 之間有什麼區別
• 在 Python 中清除列表