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 < 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