Reputation: 57
I'm getting an unexpected result from a program designed to make a list of even Fibonacci numbers. The part of the code that finds all the numbers works fine, but when it gets to the
if i % 2 != 0
fib_list.remove(i)
part something seems to go wrong, because it doesn't take out all the odd numbers. Below is the entire program. What am I doing wrong?
fib_list = [1, 2, 3]
for i in range(4, 4000001):
if (i - fib_list[-1] - fib_list[-2]) == 0:
fib_list.append(i)
print fib_list
for i in fib_list:
if i % 2 != 0:
fib_list.remove(i)
print fib_list
Upvotes: 2
Views: 279
Reputation: 8610
You are iterating over a list while modifying it. Don't do that.
[x for x in fib_list if x % 2 == 0]
Upvotes: 6