How to remove index list from another list in python?

PythonServer Side ProgrammingProgramming

We have two lists here, L1 a list object from which certain elements are to be removed, and L2 containing indices of elements to be removed.

>>> L1=[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> L2=[2, 4, 6]

In order to remove elements at indexes listed in L2, first we create enumerate object out of L1. The enumerate() function returns enumerate object which is a collection of two element tuples, corresponding to index and element in list.

Then we run a for loop   with two variables over this enumerator and compare each index with element in L2. If found, corresponding item in L1 is deleted. Here’s the solution

>>> e=enumerate(L1)
>>> for i,j in e:
if i in L2:
del L1[i]

Resultant L1 will contain elements other than those at indexes mentioned in L2

>>> L1
[1, 2, 4, 5, 7, 8]

Published on 13-Jan-2018 00:16:45