0

I'm doing a practice problem from the book automate the boring stuff. This part of the function is meant to make a nested list with the same structure as the original table containing the length of each string so I can find the longest one in each row to use later, for formatting purposes.

The end result I'm getting is [[4, 4, 5, 5], [4, 4, 5, 5], [4, 4, 5, 5]] while it should be [[6, 7, 8, 6], [5, 3, 5, 5], [4, 4, 5, 5]]. I put a print statement inside the loop in question to see what was changing with each iteration and for i = 0, j = 0, for example, it will change list[0][0], list[1][0] and list[2][0], but I can't seem to figure out why. What did I do wrong here?

def printTable(tableData):

    w = max([len(tableData[i]) for i in range(len(tableData))])
    h = len(tableData)

    colwidths = [list(range(w))] * len(tableData)

    w2 = list(range(w)) * h
    h2 = []
    for i in range(h):
        for j in range(w):
            h2 += [i]

    for i,j in zip(h2,w2):
        colwidths[i][j] = (len(tableData[i][j]))
        print(colwidths)

table = [['apples', 'oranges', 'cherries', 'banana'],
         ['Alice', 'Bob', 'Carol', 'David'],
         ['dogs', 'cats', 'moose', 'goose']]

printTable(table)

Thanks

Tim
  • 48
  • 4

0 Answers0