Q:

Python program to remove multiple elements from a list using list comprehension

0

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.

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]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now