I would expect the removal to work in the same way and the list to be the same after the two iterations that remove elements, but it is not so.
I suspect that modifying the list I am iterating on may be the cause but was also expecting that somehow this would be managed safely by the language.
Can someone help me understand what happens, why the results are different?
my_list = list(range(10))
to_remove_l = [ x for x in my_list if x%3 == 0]
to_remove_genex = (x for x in my_list if x%3 == 0)
print(f"id: {id(my_list)}")
print(my_list)
removed = []
for e in to_remove_l:
print(f"removing: {e}")
my_list.remove(e)
removed.append(e)
print(my_list)
my_list.extend(removed)
print(f"id: {id(my_list)}")
print(my_list)
to_remove_genex = (x for x in my_list if x%3 == 0)
for e in to_remove_genex:
print(f"removing: {e}")
my_list.remove(e)
print(my_list)
the output is
id: 1822749490560
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
removing: 0
removing: 3
removing: 6
removing: 9
[1, 2, 4, 5, 7, 8]
id: 1822749490560
[1, 2, 4, 5, 7, 8, 0, 3, 6, 9]
removing: 0
removing: 6
[1, 2, 4, 5, 7, 8, 3, 9]