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

Question:

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?

Asked By: Amir Zarbakhsh

||

Answers:

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
Answered By: Yamin Nather

In your example you seem to be trying to delete every item in the list, in which case you could probably just redefine the list to be empty, e.g. List_T = [].
But if you are trying to delete only certain specified indices from the list, you can loop through the list and append any indices that aren’t set for deletion, like so:

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

indices_for_deletion = [0,1,2,3,4,5]

for e,i in enumerate(List_T):

    if e not in indices_for_deletion:
        List_T_truncated.append(i)

print(List_T_truncated)

And this will print ['g', 'h', 'i', 'k']

Answered By: Oxin

when you delete the item in "list" like that, the len(list) will be change and the index from for loop go to far base on original len(list).
If u want to clear all items, why dont u use list.clear() ? or list = [] (Be careful when using the seacond in some case)

Answered By: JACOBnotpro

You shouldn’t try to change a list while you’re looping over it by index because the indices of the elements are changing, as you found out. If you look at the output of your program, you’ll see that you’re really removing ever other element (a, c, e, etc.) until you get an error.

If you want to remove each element from the front of the list, one at a time, use a while loop and pop the first element.

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

while(List_T):  # while the list is not empty
    first_element = List_T.pop(0)
    # do something with the removed value here
    print(List_T)
Answered By: Bill the Lizard
List_T = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k']

for i in range(len(List_T) - 1, -1, -1):
    List_T.remove(List_T[i])
    print(List_T)

The original code iterates over the list in order, starting from the first element. As it removes elements from the list, the list’s length decreases. This means that the index values used in the loop become invalid. For example, if the list has 10 elements, and the loop is on the 5th iteration, the i variable will have a value of 5. However, the list now only has 5 elements, so the index 5 is no longer valid.

The corrected code iterates over the list in reverse order, starting from the last element. This means that the index values used in the loop will always be valid. For example, if the list has 10 elements, and the loop is on the 5th iteration, the i variable will have a value of 9. This is still a valid index, even though the list has only 5 elements left.

Answered By: Byte

Try this:

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

for j in range(len(List_T)):
    j -= 1
    indices.append(j + 1)

for i in sorted(indices, reverse=True):
    del List_T[i]

print(List_T)
Answered By: ADIIIIB
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.