3

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

1
  • 5
    Think about what happens when x is 3 Commented May 17, 2013 at 9:42

2 Answers 2

7

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]
Sign up to request clarification or add additional context in comments.

2 Comments

[elem - close[i - 1] for i, elem in enumerate(close) if i] saves making the temporary slice
@gnibbler: nice one, I'll steal that then. :-)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.