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
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