Fibonacci Fun, For Loop VS While Loop! Question


Hey Community from Spain!
I am learning about Algorithms, Fibonnaci is simple a list with all the pairs numbers in the range (0, 400000), and I have tried to do this with a for and a while but i dont know what code is better! or what is more powerful!

For Loop:

pares = [i for i in range(0, 4000001) if i % 2 == 0]
print pares

While Loop:

j = []
x = 0
while True:
    x += 2
    if x == 400000:
print j


we can measure it (see this stackoverflow question)

the first program takes 0.68 seconds

the second program takes 0.077 seconds, which mans it is to low to measured.

personally, if speed is important, use a generator:

pares = (i for i in range(0, 4000001) if i % 2 == 0)

you would need to execute this program quit a few times to get above 0.1 second for a reliable time measurement. you could then also consider if it is not more efficient to use range better:

pares = (i for i in range(2, 4000001, 2))


Is not the first time that you help me hahah Thanks :grin:
I have done this like a PoC, probably I wont use this in the real world, but it would be interesting how do a generator.

The problem is that:

I dont understand this mistake :confused:


it seems i was wrong:

generator expressions are great, just if you need a selective range of this numbers (like all prime numbers in that range), sorry, not very useful for you


On the home page of official Python web site, there is an example Fibonacci program that uses a while loop. See

Below is the code ...

# Python 3: Fibonacci series up to n
def fib(n):
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b

Also see Wolfram MathWorld: Fibonacci Number.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.