0

I'm trying to create a multidimensional list from a loop, but something is making all the column values change simultaneously when entering a new value for a row and column causing only the last value to be preserved. I know it has something to do with how i initialize the list, but am unsure on how to fix it.

code:

sellorderprices = ["Sellorderprice", 0, 1, 2, 3, 4, 5]
buyorderprices=["Buyorderprice", 10, 11, 21, 31, 41, 51]
days=["Days",150, 120, 90, 60, 30, 0]
export_data=[[None]*3]*(len(days))

for n in range (0, len(export_data)):
        export_data[n][0]=days[n]
        export_data[n][1]=buyorderprices[n]
        export_data[n][2]=sellorderprices[n]
print(export_data)

this prints [[0, 51, 5], [0, 51, 5], [0, 51, 5], [0, 51, 5], [0, 51, 5], [0, 51, 5], [0, 51, 5]]

Marcus Grass
  • 1,043
  • 2
  • 17
  • 38

2 Answers2

0

try:

export_data=[[None for i in range(3)] for i in range(len(days))]
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39
0

You are referencing the same list when you created export_data You can avoid that by changing the code as

export_data = [[None]*3 for i in range(len(days))]

Alternatively, you can use zip to do the same thing

export_data = list(zip(days, buyorderprices, sellorderprices))
# [('Days', 'Buyorderprice', 'Sellorderprice'), (150, 10, 0), (120, 11, 1), (90, 21, 2), (60, 31, 3), (30, 41, 4), (0, 51, 5)]

Or

export_data = [list(e) for e in zip(days, buyorderprices, sellorderprices)]
# [['Days', 'Buyorderprice', 'Sellorderprice'], [150, 10, 0], [120, 11, 1], [90, 21, 2], [60, 31, 3], [30, 41, 4], [0, 51, 5]]
Sunitha
  • 11,777
  • 2
  • 20
  • 23