Adam Siwiec
Adam Siwiec

Reputation: 973

Why do I get a Type Error with this code in python?

def word(longest):
   max_length = 0;
   words = longest.split(" ")
   for x in words:
      if len(words[x]) >  max_length:
        max_length = len(words[x])

   return max_length

word("Hello world")

Exact Error:

TypeError: list indices must be integers, not str

Im still a noob at this so please, no mean comments.

Upvotes: 2

Views: 45

Answers (2)

schafle
schafle

Reputation: 613

Because you are using x as index, when it is actually the string itself.

You can do:

for x in words:
      if len(x) >  max_length:
        max_length = len(x)

Upvotes: 3

kindall
kindall

Reputation: 184101

When you do for x in words, x is a word. So you don't need words[x] to get the word. words[x] expects x to be an integer, but it's a string, which is why you get that error.

So you should write:

for x in words:
    if len(x) >  max_length:
        max_length = len(x)

Upvotes: 3

Related Questions