I have the following code:
abc = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for i in range(0,len(abc),3):
abc.remove(abc[i])
gives me the following error:
IndexError: list index out of range
I have tried printing the value of the variable i and manually eliminating the elements of the list with that same value and it works. However this code works:
for i in range(len(alphabet), 1, -1):
if i % 3 == 0:
alphabet.pop(i-1)
from what I understand it does the same thing but in reverse order.
Could someone make me open my eyes a little about it, I don't understand the logic of what I have wrong.
In this case, the error occurs because you are decreasing the original size of the list as you go through it, so the value of the index at a given moment becomes greater than the size of the list.
abc = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l' , 'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', ' X and Z']
Initially abc has a length of 27, for each iteration the size of the list is reduced by 1 and 3 are added to the index, so
Visual understanding of what is happening:
index position => 0 => 3 => 6 => 9 => 12 => 15 => 18 => 21 => 24 => 27
list size => 27 => 26 => 25 => 24 => 23 => 22 => 21 => 20 Error: Index out of range
Because the list has 20 elements and the index would go to position number 21.
In the 2nd way proposed, it does not give an error, since the index would never be greater than the size of the list, since it is reduced instead of increased, being a better approach to the solution.
I hope you have understood and served you!
I think what happens is that by the Remove() method you cannot remove elements from a list using an index, but you can remove a specific element from a list, not use a variable and have it iterate through the list. However, since in this case what you want is to eliminate an element by means of the index, going through the list by means of the variable[i] you must use the pop method.