0

I'm trying to run a for loop in python that looks like this:

data = np.linspace(0.5, 50, 10)

output = []
for i in data:
  x = data[i] - data[i+1]
  output.append(data)

but I keep getting the error:

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

For reference I want the code to do the following:

  • x1 = x = data[0] - data[1]

  • x2 = x = data[1] - data[2] ...

and output it to the list.

Any help would be really appreciated

1
  • 3
    for i in data loops over the elements. You probably want for i,el in enumerate(data) Commented Mar 10, 2022 at 21:16

3 Answers 3

5

There are several things going on here:

  • You are iterating over the actual elements, not their index. To iterate over the indexes you can do something like this for index in range(len(data) - 1)).
  • As shown above, you want to iterrate until len(data) - 1 in order to avoid getting out of bounds.
  • It seems that you are calculating x but eventually append data instead.
  • To achive readable code, it is important to give variables meaningful names (i and x are not meaningfull).
data = np.linspace(0.5, 50, 10)

output = []
for index in range(len(data) - 1):
  result = data[index] - data[index + 1]
  output.append(result)
Sign up to request clarification or add additional context in comments.

Comments

0

for i in data: loops directly over data, thus i will be each element in data, not its index. If you need the index, use enumerate():

output = []
for i, elem in enumerate(data):
  x = data[i] - data[i+1]
  output.append(data)

However, that won't work, due to an out-of-bounds error that will occur at the very end. Instead, you can use built-in numpy functionality:

output = data[:-1] - data[1:]
print(output)

Output:

array([-5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5])

Or possible solutions:

np.full(9, -5.5)
np.ones(9) * -5.5

Comments

0

IIUC, you want to calculate the successive differences, but reversed. You can use numpy.diff

np.diff(data[::-1])[::-1]

Other option, shift the array by taking a slice of all but the last/first element and subtract:

data[:-1] - data[1:]

Output: array([-5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5])

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.