I have just discovered a very strange behaviour of list.delete()
in my program. I am currently doing the second problem of the Project Euler, in which you have to get the sum of all even fibonacci numbers until 4 million. I created all of them in a list adn then wanted to iterate through them in order to find out all not even numbers and remove them. Here is the code I have:
print(fibonacci)
for zahl in fibonacci:
print(zahl, end=' ')
if zahl%2 != 0:
print('not even')
fibonacci.remove(zahl)
else:
print('even')
Which gives:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578]
1 not even
2 even
3 not even
8 even
13 not even
34 even
55 not even
144 even
233 not even
610 even
987 not even
2584 even
4181 not even
10946 even
17711 not even
46368 even
75025 not even
196418 even
317811 not even
832040 even
1346269 not even
3524578 even
7465174
Strangely some numbers are missing!
5 and 377 for example (and some more). Now here it comes. If I comment out the fibonacci.delete(zahl)
line, they are printed there, declared correctly as not even.
Where is this behavoiour coming from. Could it come from me affecting the list I'm iterating through?
I an not sure about that, but I'd really like to know. I googled for this phenomenon , but didn't find anything that was solveing my problem or explaining where it comes from.
I' like to know two things
Is the behaviour coming from me affecting the list I'm iterating through?
How can I correct that?