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

Marc Tompkins marc.tompkins at gmail.com
Fri Aug 15 21:22:34 CEST 2014


On Fri, Aug 15, 2014 at 10:46 AM, Terry--gmail <terry.kemmerer at gmail.com> wrote:

(By the way - your indentation got flattened - cue the inevitable
chorus of "DON'T POST TO THIS LIST IN HTML" - so this is my best-guess
reconstruction.)
> lens = []
> # pre-format the list called lens for maximum number of columns contained in
> catalog2
> lens = [0] * len(catalog2[0])
> # map the largest sizes of each column into list 'lens'
> col, line_number = 0, 0
> for line_number in range(len(catalog2)):
>     for col in range(len(catalog2[line_number])):
>         if lens[col] < len(catalog2[line_number][col]):
>             lens[col] = len(catalog2[line_number][col])

There are two separate issues here - the syntactic mistake that's
giving you the error, and the non-Pythonic nature of "for col in
range()" - let's deal with the first one.

catalog2 is a list containing lines; line_number is a list containing
integers.  catalog2[line_number][col] is an integer; len(int) gives
you a TypeError, as you've seen.
I don't entirely understand what you're trying to do, so I can't tell
you whether you want
>         if lens[col] < len(catalog2[line_number]):
or
>         if lens[col] < catalog2[line_number][col]:
but it's probably one or the other.


Now, for the second issue - to take the length of a list and use that
as the limit for a one-by-one crawl through the list is not the Python
way.  Rather than:
> for line_number in range(len(catalog2)):
use
> for line_number, item in enumerate(catalog2):

https://docs.python.org/3/tutorial/datastructures.html#looping-techniques


More information about the Tutor mailing list