[Tutor] Building Starships -- object of type 'int' has no len()

Peter Otten __peter__ at web.de
Wed Aug 20 23:18:31 CEST 2014


Terry--gmail wrote:

> Marc, my understanding is, is that:
> 
>      lens[col].append(len(item))
> 
> -should be building a mirror image of my list of lists called catalog2,
> which currently has 9 columns by x number of rows, and that we are
> plugging into these positions, the sizes of all the elements in that
> block of data.
> 
> If that is true, then lens[col] is creating lists which contain the
> sizes of the elements in that particular column.
> 
> So, I completely don't understand why we would eliminate the positioning
> of which list we are referencing in lens by saying:
> 
>      lens.append(len(item))
> 
> It seems to me that, that statement would put the entire block of
> element sizes into one list, and the next MAX statement would then yield
> only a single number, which would be the largest size element it
> encounted in the whole of catalog2!
> 
> Or am I really missing the boat here? :)

[Alan Gauld]

> lens = [] * len(catalog2[0])
> for row in catalog2[1:]:   # miss the first row
>      for col,item in row:
>         lens[col].append(len(item))
> 
> lens = [max(col) for col in lens]
 
In the above snipped Alan introduced introduced another bug that wasn't 
fixed in any of the posts I saw: lens should be a list of lists. 

With "lens" referring to

 [[], [], [], ...]

lens[n] refers to the n-th list and thus

lens[col].append(len(item))

appends the items's length to the respective column/list. 
The complete fixed code is then:

# make a list with one empty list per column
lens = []
for item in catalog2[0]:
    lens.append([])

for row in catalog2:
    for col, item in enumerate(row):
        lens[col].append(len(item))

lens = [max(col) for col in lens]


The first for-loop can also be written as a list comprehension:

lens = [[] for item in catalog2[0]]

You might be tempted to simplify further

# WRONG:
lens = [[]] * len(catalog2[0])

but that repeats the same inner list len(catalog2[0]) times where you 
actually need len(catalog2[0]) distinct lists.



More information about the Tutor mailing list