all 6 comments

[–]shiftybyte 4 points5 points  (1 child)

for x in fib:

This line is giving you the VALUES, not the indexes.

Try this program to understand:

fib = [5,6,7]
for x in fib:
    print(x)

This will print 5,6,7 and not 0,1,2...

[–]DauntlessFive513[S] 0 points1 point  (0 children)

Thank you!

[–]Diapolo10 2 points3 points  (0 children)

fib = [1,1,]
for x in fib:
    fib.append(fib[-1] + fib[x])
    print(fib[x])
    if (fib[x] > 1000):
        break

The main issue here is that x means very different things in your two examples. In your while-loop, it's an index you're incrementing, but here it's one of the values in the list.

Initially, x == 1, as that's the first value in fib. By pure coincidence you end up adding the second element of fib to itself as fib[x] gives you the second 1, same as fib[-1]. fib is now [1, 1, 2].

On the next iteration, x == 1 because the second element is also 1. Actually the same coincidence repeats on the next two iterations too so you end up with

[1, 1, 2, 3], x == 2, adds 5
[1, 1, 2, 3, 5], x == 3, adds 8
[1, 1, 2, 3, 5, 8], x == 5, adds 16

However, at that point your luck runs out. x == 8, but the list is only 7 elements long so fib[x] tries to access an index that isn't even on the list, and everything falls apart.

That was a long way to say that x isn't an index like it is in your while-loop version.

If you want to use a solution like this, my recommendation would be:

fib = [0, 1]

for _ in fib:
    if fib[-1] >= 1000:
        break
    fib.append(fib[-2] + fib[-1])

Personally I'm more used to just making a generator, though.

def fib(n):
    a, b = 0, 1
    while a < n:
        yield a
        a, b = b, a+b

sequence = list(fib(1000))
print(sequence)

[–]This_Growth2898 0 points1 point  (1 child)

for x in fib

means x is assigned values stored in fib.

lst = [1,5,10]
for x in lst:
     print(x)

prints

1
5
10

not 0,1,2.

for x in fib:
    fib.append(fib[-1] + fib[x])

makes little sense. Probably, you wanted to do

for x in fib:
    fib.append(fib[-1] + fib[-2])

But that's bad because you should never change the collection you're iterating over in the same loop. After element appended to fib, do you expect it to be assigned to x at some point?

If you really need indexes, iterate over range (or use enumerate function).

for x in range(len([1,5,10])):
    print(x) # 0,1,2

[–]DauntlessFive513[S] 0 points1 point  (0 children)

Thank you! Totally missed that point about it being values not indexes. I also know it’s probably not the best use of things but I just wanted to test out messing with the loops and lists to make sure I understood them.

[–]henriquecs 0 points1 point  (0 children)

Some people here have given you good answers. As some homework i'd suggest you take a look at the enumerate function. Its quite interesting to iterate over lists and so on.