Ok, this is bizarre. I don’t understand and it’s getting extremely frustrating.
- I declare and array (list)
- I initiate the first row with strings (stock symbols)
- I populate the rest with zeros for the required number of trading days.
-
The I want to populate certain elements of the ‘positions’ matrix with a number for stocks to be purchased or sold on that day. And instead of populating only the one element, the entire column populates.
# Initiating position matrix positions = [] # Initiating a row of zeros (to fill position matrix later) empty_row = [] # Symbols is a list of symbols that will be traded. for symbol in symbols: empty_row.append(0) # First row of positions will be symbols positions.append(symbols) # All other rows will be empty_rows for day in timestamps: positions.append(empty_row)Then I will determine what element of “positions” I need to populate. Let’s say the element on the 10th row and 1st column (indexing from zero). So i do:
positions[10][1] = 100
The result I get is that the ENTIRE column 1 is full of 100s. Not just the element. What am I doing wrong?
You’re appending the same empty list over and over:
You need to create a new “empty” list for each new row:
You can put all that into a list comprehension, so your entire code would become