0

As part of a program to make nice tables to save in txt files, I had some code like this:

    data=[[1,2,3],[4,5],[6,7,8]]
    output=[['']*len(data)]*3
    rowNum=0
    for row in data:
        for subColNum in range(3):
            if subColNum >= len(row):
                output[subColNum][rowNum]=''
            else:
                output[subColNum][rowNum]=row[subColNum]
        rowNum+=1
    print(output)

I wanted this to output:

[[1,4,6],[2,5,7],[3,'',8]] but instead got [[3, '', 8], [3, '', 8], [3, '', 8]]

the problem seems to be with the line: 'output[subColNum][rowNum]=row[subColNum]' which somehow seems to be assigning multiple items at once, as opposed to one per iteration as I expected.

1 Answers1

1

This problem comes up when using the multiplication symbol to give the list a certain length.

Your code should work when you create the list at runtime:

output = []

for row in date:

    output.append([]) 

    for ColNum in range(3):

        output[ColNum].append(valueYouWantHere)