2

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
Chandrew
  • 59
  • 5

1 Answers1

6

You are iterating over a list while modifying it. Don't do that.

[x for x in fib_list if x % 2 == 0]
zhangyangyu
  • 8,520
  • 2
  • 33
  • 43
  • Oh. Is there a way to independently evaluate each item in a list and then perform an action on it and avoid the iterating-while-modifying problem? – Chandrew Jul 13 '13 at 16:39
  • Also, in the code you've posted it looks like the first x must be referring to something different than the other x's... Can you call a function like this? – Chandrew Jul 13 '13 at 16:40
  • @user2579517 This solution does exactly that - in words, it loops over `fib_list` and grabs all `x` such that `x % 2 == 0`, creating a new list in the process so the original list is untouched. – Sajjan Singh Jul 13 '13 at 16:40
  • Actually my code does what you want. It is a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html). It is a feature of Python. It does the same thing as `for x in fib_list: if x % 2 == 0: new_list.append(x)`. This will not modify the original list but will generate a new one. So, it may not be memory efficient. But you have to do this avoid the error. Or you can use `(x for x in fib_list if x % 2 == 0)`, this will generate a [generator](http://stackoverflow.com/questions/364802/generator-comprehension), another feature in Python. It is memory efficient.@user2579517 – zhangyangyu Jul 13 '13 at 16:46