0
I’m solving a question where I need to insert 5 values in a list, add all the numbers in that list and take out their arithmetic media, then I need to remove from the list all the numbers that are less than average.
my code is like this:
numeros = []
for x in range(0, 5):
num = int(input("Digite um numero: "))
numeros.append(num)
media = int(sum(numeros) / 5)
for x in numeros:
if x < media:
numeros.remove(x)
print(f'\nA media é: {media}')
print(numeros)
Until the part of taking the average is worked, but when removing the number, it always leaves a lower than the average in the list, example of input:
Digite um numero: 2
Digite um numero: 3
Digite um numero: 4
Digite um numero: 5
Digite um numero: 6
Exit:
A media é: 4
[3, 4, 5, 6]
The program removed 2 but did not remove 3, how can I fix this?
If you remove items from the list while iterating it will surely generate unforeseen behavior. Instead of iterating through the eternal list by a clone of that list on the line
for x in numeros:
swap forfor x in numeros[:]:
.Or do a filtration like this example– Augusto Vasques
you saved me, thank you
– José Guilherme Lins
The above links in the blue box explain in detail why it is not a good thing to remove items from a list in the same loop that iterates over it, and give some solution alternatives
– hkotsubo