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
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:
close.enumerate() to generate an index for each element, giving us both the index i and the element elem.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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With