Search code examples
pythonarrayssubtraction

Value assigned to array element comes out as zero


Question: Why does a list element to which I assign a non-zero value become zero?

Have a list called eta, which contains a lot of different values. With this list want to make a new list a, in which each element a[i], is equal to eta[i+1]-eta[i]. The value for eta[i+1]-eta[i] can be calculated and can check that it gives me a non-zero value, but when I make a for loop and run it for i in some range, it sets a[i] = 0 for some reason.

Here is the code:

import numpy as np

a = np.arange(5)
for i in range(5):
    a[i] = eta[i+1]-eta[i]

Tried printing the values for eta[i+1]-eta[i] for each step and it comes out as a non-zero number, but if print a[i] it comes out as zero. Screenshot of code with prints.


Solution

  • You need to specify the data type when calling np.arange() or else it will infer that the indexes should be ints as the parameter passed in is 5 (an int).

    Something like this will work.

    a = np.arange(5, dtype='float')
    

    Read more about dtypes here: https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.dtype.html#numpy.dtype