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

Deleting from a list in Python with a [FOR] loop based on [index]

I have a list that I want to remove from the list based on the index of each element, but when it reaches the middle of the list, because the length of the list of elements has decreased, I face the following error.

code:

List_T = ['a','b','c','d','e','f','g','h','i','k']
for i in range(len(List_T)):
     List_T.remove(List_T[i])
     print(List_T)

Error:
IndexError: list index out of range

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

How can I do my deletion based on the index of each element without getting this error?

>Solution :

Start removing elements starting from the back of the list, like this

List_T = ['a','b','c','d','e','f','g','h','i','k']
for i in reversed(range(len(List_T))):
     List_T.remove(List_T[i])
     print(List_T)

or if you just want to delete everything in the list you could just use the clear() function and make this a one liner.

List_T = ['a','b','c','d','e','f','g','h','i','k']

List_T.clear() # List_T is empty now
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