Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing elements from a list based on indices in another list in Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[6,9]

>Solution :

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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading