3
I need to remove an item from a list during an iteration over the list itself.
The reason to remove during the loop is that if this item remains may end up triggering other triggers within the loop which would lead to a false result since the tests I do on the object within the list should be sequential.
What is the most appropriate (efficient/idiomatic) way to remove an object from a list when iterating over it?
lista=[] # Lista de obejos ativos.
class teste():
ent = 0
sai = 0
def alt(i):
t = teste()
t.ent = i
t.sai = 2*i
lista.append(t)
print(t.ent,t.sai)
def objetos_ativos(x):
print('O objeto ({} , {}) está ativo: '.format(x.ent, x.sai))
for i in range(5):
alt(i)
print('')
# Se usar ' lista.copy() ' para fazer a iteração sobre a lista,
# x irá acionar a 'def objetos_ativos' e printar (20 , 4) como objeto ativo.
for x in (lista.copy()):
# Trecho com problema
if x.sai==4: # Se objeto 'x' falhar nesse teste ele é desativado imediatamente.
lista.remove(x)
#
x.ent = x.ent * 10
# Segundo teste que se o objeto foi desativado não deve participar.
if x.ent >= 1:
objetos_ativos(x)
for x in lista:
print(x.ent, x.sai)
The entrance is:
0 0
1 2
2 4
3 6
4 8
And I waited for the exit as:
0 0
10 2
30 6
40 8
But instead it returns:
0 0
10 2
3 6
40 8
have to use the word
continue
to move to the next iteration or to exit the loop if there is no more, so you will not try to make "x.ent = x.ent * 10" an error, I suppose.– André
Thanks for the tip @André this along with the hkotsubo solution was exactly what I was looking for.
– Thales Almeida