Project Euler #2: sum of even Fibonacci numbers, using generators I am currently working on Project Euler problem #2 which requires you to print the sum of all even fibonacci numbers below 4 million.

I just recently learned about generators and from my understanding they are used to decrease memory consumption by generating values on the fly (and not storing them in a huge list).

Does this still work when used in a for loop or will it just generate all values, store them in a list and then loop through them?

for n in some_generator(): pass


In my specific case the code looks like this:

def fibonacci(n): # yields all fibonacci numbers below n
    second_last_n = 0
    last_n = 1
    while (last_n &lt; n):
        current_n = second_last_n + last_n
        second_last_n = last_n
        last_n = current_n
        yield current_n

def filter_even(nums): # yields all numbers in nums (a generator) which are even
    for n in nums:
        if (n % 2 == 0):
            yield n
It's weird that the fibonacci() generates a sequence that starts with 1, 2, 3, 5, 8, ….  Conventionally, the Fibonacci sequence starts with either 0, 1, 1, 2, 3, 5, 8, … or 1, 1, 2, 3, 5, 8, ….

A purer approach would be to use [itertools.takewhile()] in conjunction with an infinite generator.

You should also take advantage of parallel assignment.

The fibonacci() generator would look like this:

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b


filter_even() is fine.  You could also just write a generator expression instead.

from itertools import takewhile

print(sum(n for n in takewhile(lambda n: n &lt; 4000000, fibonacci()) if n % 2 == 0))