Reno
Reno

Reputation: 1139

While loop python

I am new to python and am having problems seeing why this code does not work. I would like it to return [10,122,2].

close = [5000,5010,5132,5134]

def difference():
    x = 0
    data = []
    while x < len(close):
        diff = close[x+1]-close[x]
        data.append(diff)
        x = x + 1
    return data

it returns "IndexError: list index out of range" but my understanding was that the while loop only runs when the condition is met. What am I missing? Thanks

Upvotes: 3

Views: 848

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121256

You limit x to be smaller than len(close), but the last index of a list is at len(close) - 1 (0 based indexing). This means in the last iteration of your loop x + 1 will be equal to len(close) and out of bounds.

This works:

while x < len(close) - 1:
    diff = close[x+1]-close[x]
    data.append(diff)
    x = x + 1

Your code can also be simplified to:

data = [elem - close[i - 1] for i, elem in enumerate(close) if i]

This list comprehension:

  • Loops over all elements in close.
  • Uses enumerate() to generate an index for each element, giving us both the index i and the element elem.
  • Calculates the difference between the current element and the previous element in close (using the index - 1), except when the index is 0, effectively skipping the one element for which there is no preceding element in close.

Demo:

>>> close = [5000,5010,5132,5134]
>>> [elem - close[i - 1] for i, elem in enumerate(close) if i]
[10, 122, 2]

Upvotes: 7

kampu
kampu

Reputation: 1421

see this: close[x+1]

That's the problem. Indeed x will always be a valid index according to the condition you wrote. But in the final iteration, you will find that x+1 is not. If you want to avoid going out of range in this line, you will have to subtract 1 from the maximum value you are checking against.

Upvotes: 2

Related Questions