Removing elements from a list based on indices in another list in Python
Question:
I have a list J
. I want to remove specific elements from J[0]
based on index
. For example, I want to remove J[0],J[3]
based on elements in index
. But I am getting an error. I present the expected output.
J=[[2, 6, 9, 10]]
index=[[0,3]]
for i in range(0,len(J)):
for k in range(0,len(index)):
J[i].remove(index[k][0])
print(J)
The error is
in <module>
J[i].remove(index[k][0])
ValueError: list.remove(x): x not in list
The expected output is
[6,9]
Answers:
Try list comprehension / filtering (and fix the [0]
as required):
new_J = [j for i,j in enumerate(J[0]) if i not in index[0]]
Well in this code you loop your code only 1 time for j and index because both len(j) and len(index) is 1.
Try this:
J=[2, 6, 9, 10]
index=[0,3]
for i in range(len(index)):
J.pop(index[i] - i)
print(J)
I have a list J
. I want to remove specific elements from J[0]
based on index
. For example, I want to remove J[0],J[3]
based on elements in index
. But I am getting an error. I present the expected output.
J=[[2, 6, 9, 10]]
index=[[0,3]]
for i in range(0,len(J)):
for k in range(0,len(index)):
J[i].remove(index[k][0])
print(J)
The error is
in <module>
J[i].remove(index[k][0])
ValueError: list.remove(x): x not in list
The expected output is
[6,9]
Try list comprehension / filtering (and fix the [0]
as required):
new_J = [j for i,j in enumerate(J[0]) if i not in index[0]]
Well in this code you loop your code only 1 time for j and index because both len(j) and len(index) is 1.
Try this:
J=[2, 6, 9, 10]
index=[0,3]
for i in range(len(index)):
J.pop(index[i] - i)
print(J)