Home » Python » Python programs

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

Here, we are going to learn how to remove multiple elements from a list using list comprehension in Python programming language?
Submitted by IncludeHelp, on April 03, 2020

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]

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]





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.