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 of one list wth respect to the other in Python

I have lists J and Indices. I want to remove elements of J according to locations specified in Indices. For example, Indices[0]=1 and Indices[1]=2. This means that J[0][1] and J[0][2] should be removed in one go. But I am getting an error. I present the expected output.

Indices=[1,2]
J=[[2, 3, 6, 7, 9, 10]]


J=J[0].remove(Indices[0])
print(J)

The error is

in <module>
    J=J[0].remove(Indices[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

[[2, 7, 9, 10]]

>Solution :

Use this

Indices = [1, 2]
J = [[2, 3, 6, 7, 9, 10]]

for index in sorted(Indices, reverse=True):
    J[0].pop(index)

print(J)

remove: remove the element that is passed in it, error if the element is not in the list.

pop: remove the element on the index that is passed in it, if no index provide then it will remove the last element[-1 index], if the index is not correct then error.

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