As explained here, here and here, remove elements from a list in it loop that iterates on it can cause these problems. To illustrate better, let’s modify a little the loop:
letras = ["A", "B", "C", "B"]
for indice, letra in enumerate(letras):
print(f' antes: {indice}={letra} - lista={letras}')
letras.remove(letra)
print(f'depois: {indice}={letra} - lista={letras}')
I use enumerate
to iterate through the indexes and their elements at the same time. The output is:
antes: 0=A - lista=['A', 'B', 'C', 'B']
depois: 0=A - lista=['B', 'C', 'B']
antes: 1=C - lista=['B', 'C', 'B']
depois: 1=C - lista=['B', 'B']
That is, in the first iteration (when the index is 0), the letra
corresponds to the first element (index zero), which is the letter "A". After removing it, the list becomes ['B', 'C', 'B']
.
In the second iteration (when the index is 1), letra
corresponds to the second element of the list. But since the list has been modified and "A" has been removed, the second element (which is at index 1) is the letter "C". Therefore the first "B" is skipped.
To documentation gives you some alternatives to avoid this problem and do what you want. Or you create another list with the elements you want (that is, everything that is not a vowel):
letras = ["A", "B", "C", "B"]
vogais = ["a", "e", "i", "o", "u"]
resultado = []
for letra in letras:
if letra.lower() in vogais:
print(letra.upper())
else:
print(letra)
resultado.append(letra)
print(resultado)
Or you iterate over a copy of the list:
letras = ["A", "B", "C", "B"]
vogais = ["a", "e", "i", "o", "u"]
for letra in letras.copy(): # itero sobre uma cópia
if letra.lower() in vogais:
print(letra.upper())
letras.remove(letra) # agora posso remover, pois não afeta a cópia
else:
print(letra)
Also note that you don’t need elif
. In the if
you see if the letter is in the vowel list. If so, enter if
, and whether it arrived at the else
, it is because it is not, so it is redundant and unnecessary to test it again.
Must have the same value in the two "B" see there.
– Edu Mendonça