Home python TypeError: list indices must be integers or slices, not str

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

Author

Date

Category

I need to write a function that, using for , goes through the list and displays the state name and the number of letters in it.

newEngland = ["Maine", "New Hampshire", "Vermont", "Rhode Island",
"Massachusetts", "Connecticut"]
def how_many_let (ne):
  lis = ne
  for i in lis:
    num_let = len (lis [i])
    print (i, 'has', num_let, 'letters')

I get the error:

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

I don’t know how to fix this error. I would be grateful for any help.


Answer 1, authority 100%

You use for to step through the lis list, and the lis list is a list of strings. Accordingly, i contains a string, hence the error that i (string) cannot be used as an index (lis [i] ). In your case, indices are not needed at all, just keep in mind that when you loop through the list, you get the strings themselves from the list, not the indices:

def how_many_let (ne):
  lis = ne
  for word in lis:
    num_let = len (word)
    print (word, 'has', num_let, 'letters')

A couple more points:

  1. Note that the assignment to lis = ne does not copy the list. In principle, this operation is not needed here, but for some reason you inserted it, so just in case I warn you)
  2. When outputting multiple arguments via print , spaces are automatically inserted between them. Extra spaces in the lines 'has' and 'letters' are not needed in this case.

If you still need string indices, you can use the enumerate function:

for i, word in enumerate (lis): # word gets a string from the list, and i - its index
  ...

Answer 2, authority 50%

SPISOK_GORODOV = ["Maine", "New Hampshire", "Vermont", "Rhode Island",
"Massachusetts", "Connecticut"]
for GOROD in SPISOK_GORODOV:
  DLINA_GORODA = len (GOROD)
  print (GOROD, 'has', DLINA_GORODA, 'letters')

In your code, it is not the index i that is processed, but specifically each element of the list, in this case the strings. It looks like you were guided by the logic of other programming languages ​​when writing this series.


Answer 3, authority 50%


def count_letters (name):
  for one in name:
    name_len = len (one) - one.count ("") # number of letters in the name, excluding spaces
    print (f '{one} contains {name_len} letters in name')
newEngland = ["Maine", "New Hampshire", "Vermont", "Rhode Island", "Massachusetts",
"Connecticut"]
count_letters (newEngland)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions