user8792756
user8792756

Reputation: 11

Python 3.6.2 - Finding the length of the longest string in a sublist and store that value in an existing list

I'm working through "Automate the Boring Stuff With Python." One of the projects wants me to:

a) create a list to store the length of the longest string in each sublist, colWidths.

b) find said length of the longest string in each sublist in the tableData list

c) store the length back into colWidths

Here's my code:

def printTable(alist):
    colWidths = [0] * len(alist)
    for i in alist:
       colWidths[i] = len(max(i, key=len))
       print(colWidths(i))


tableData = [['apples','oranges','cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]
printTable(tableData)

#TODO: Make each list into a column that uses rjust(n) to justify all of 
#the strings to the right n characters

Whenever I run this code, I get this error on line 4:

TypeError: list indices must be integers or slices, not list

Why can't I use colWidths[i] to take the result of len(max(i, key-len)) and store it in the respective colWidths value?

Upvotes: 1

Views: 301

Answers (1)

Dor-Ron
Dor-Ron

Reputation: 1807

A for..in loop uses the items stored in each index every iteration one-by-one. You're attempting to index a list with another list in this case, since alist is a 2-d list. What you want to do is for i in range(len(alist)): that way you're using numbers to index colWidths instead of an actual list, which is invalid.

Upvotes: 0

Related Questions