Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 833
Reno Avatar asked Mar 13 '26 00:03

Reno


2 Answers

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]
like image 105
Martijn Pieters Avatar answered Mar 14 '26 14:03

Martijn Pieters


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.

like image 33
kampu Avatar answered Mar 14 '26 16:03

kampu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!