pythonvariable-length

Getting wrong answer from data length calculation


I have a list of 41 data from a functioned I defined, but I only want to access the first 40 of them. So, the index positions I am looking for are from 0 - 39

forecast_price(10)[:len(forecast_price(10)) - 1] 

I also made it a variable for easier reference further on in my codes:

forecast_w10 = forecast_price(10)[:len(forecast_price(10)) - 1] 

However, when I try printing the length of data in the variable, I still get 41. I feel like the mistake is right under my nose but can't seem to figure it out. What am I doing wrong?

In[46]: print(len(forecast_w10))
Out[46]: 41

Solution

  • For reproducibility, let's assume forecast_price is a function that returns a list of 41 elements, starting at a given initial value x:

    def forecast_price(x):
        return [i + x for i in range(41)]
    
    print(forecast_price(1))          # [1, 2, 3, ..., 39, 40, 41]
    print(len(forecast_price(1)))     # 41
    
    print(forecast_price(10))         # [10, 11, 12, ..., 48, 49, 50]
    print(len(forecast_price(10)))    # 41
    

    Since you want to access only the 40 first values, use the slicing operator:

    forecast_w10 = forecast_price(10)[:40] 
    print(forecast_w10)               # [10, 11, 12, ..., 47, 48, 49]
    print(len(forecast_w10))          # 40