Project Euler #2 in Python Here is my Python code for Project Euler #2:


  Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:
  
  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
  
  By considering the terms in the Fibonacci sequence whose values do not
  exceed four million, find the sum of the even-valued terms.


How well did I do and what improvements can I make?

sum = 0
fib = []
i = 2

fib.append(0), fib.append(1), fib.append(1)
while fib[i] &lt; 4000000:
    i += 1
    fib.append(fib[i-1] + fib[i-2])
    if (fib[i] % 2 ==0):
        sum += fib[i]

print sum


EDIT: Thanks everyone for answering and commenting. All answers and some comments provide different suggestions which is very helpful.
Your use of an array to store previous entries is convenient, but it requires a lot of memory use for values that will be thrown away and not reused. It's very simple to keep the two most recent values in simple variables, and not have the array at all.

Consider:

sum = 0
current = 1
previous = 1

while True:
    fib = current + previous
    if (fib &gt; 4000000):
        break

    previous = current
    current = fib

    if (fib % 2 == 0):
        sum += fib

print sum


By eliminating the array you save a lot of management time, and space.

The code above contains a break condition inside the infinite loop instead of a loop condition. This is a common practice solution in Python for a do-while loop instead of a while-do loop.