-1

I am trying to traverse a 2d array with a nested for loop, and it has different values when I graph it, but when I try to access the data, it the elements are all the same. I have tried different styles of for loops but get the same errors. This is more of an error that I don't understand coming from Java.

predicted_values = 2*[2*[0]] #  number of lines *[ number of data points *[0]]

for row in predicted_values:

    #last given price
    row[0] = adj_close[len(adj_close)-1] 

    for index in xrange(1,len(row)):

        random_float_0_1 = random.random()
        drift = meanPDR -variance/2
        random_offset = standard_deviation*norm.ppf(random_float_0_1)
        t = drift + random_offset
        predicted_stock_price = row[index-1]*math.exp(t)
        row[index] = predicted_stock_price
        print predicted_values

    plt.plot(range(0,len(row)),row)

This outputs

[[152.186905, 149.88609120889242], [152.186905, 149.88609120889242]]
[[152.186905, 151.0754945683822], [152.186905, 151.0754945683822]]

when I want it to output

[[152.186905, 149.88609120889242], [152.186905, 0]]
[[152.186905, 149.88609120889242], [152.186905, 151.0754945683822]]

What happened to overwrite the previous data that it shouldn't have access to.

1 Answers1

1

The problem isn't the loops: it's that you don't realize the semantics of Python list short-hand. Here's your nested list with a shorter name and a simple change:

>>> pv = 2*[2*[0]]
>>> pv
[[0, 0], [0, 0]]
>>> pv[0][1] = "new"
>>> pv
[[0, 'new'], [0, 'new']]

The problem is that you didn't make four independent elements: you made two references to the same 2-element list.

Here's the overkill version:

>>> pv = [[0 for col in range(2)] for row in range(2)]
>>> pv
[[0, 0], [0, 0]]
>>> pv[0][1] = "new"
>>> pv
[[0, 'new'], [0, 0]]
>>> pv[1][0] = "abc"
>>> pv
[[0, 'new'], ['abc', 0]]

Does that get you moving?

Keep in mind that variables in Python are all indirect: a reference to a value.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • Is this how I am supposed to initialize any 2d array in python? I am coming from java so this seems strange. – DavidCincotta May 18 '17 at 22:36
  • Nope; see the answers under the question referenced in the "duplicate" closing of this one. I was looking for it when `ImportanceOfBeingErnest` beat me to it. – Prune May 18 '17 at 22:39