We can remove elements from multiple indices in a list using this syntax,
我们可以使用以下语法从列表中的多个索引中删除元素,
indices = index1, index2, ...
list_name = [i for j, i in enumerate(list_name) if j not in indices]
Here, we are implementing a python program to remove multiple elements from a list using list comprehension.
在这里,我们正在实现一个python程序,以使用list comprehension从列表中删除多个元素 。
Example:
例:
Input:
list1 = [10, 20, 30, 40, 50, 60, 70]
indices = 0, 2, 4
Output:
list1 = [20, 40, 60, 70]
Input:
list1 = [10, 20, 30, 40, 50, 60, 70]
indices = 1, 3
Output:
list1 = [10, 30, 50, 60, 70]
Program:
程序:
# Python program to remove multiple elements
# from a list using list comprehension
list1 = [10, 20, 30, 40, 50, 60, 70]
# printing the list
print("The list is: ")
print(list1)
# list comprehension, removing elements
indices = 0, 2, 4
list1 = [i for j, i in enumerate(list1) if j not in indices]
# printing the list after removeing elements
print("After removing elements, list is: ")
print(list1)
Output
输出量
The list is:
[10, 20, 30, 40, 50, 60, 70]
After removing elements, list is:
[20, 40, 60, 70]