2

So I have a list for a school assignment.

newEngland = ["Maine","New Hampshire","Vermont", "Rhode Island", 
"Massachusetts","Connecticut"]

I have to write a code using a "for" loop to isolate each individual element in the list and count the number of letters in that element. Output should look something like so

In [70]: problem2_3(newEngland)
Maine has 5 letters.
New Hampshire has 13 letters.
Vermont has 7 letters.
Rhode Island has 12 letters.
Massachusetts has 13 letters.
Connecticut has 11 letters.

The code i write has to work for any other list that someone wanted to test it on so it can not be specific to this list

My first idea was to write the following

def problem2_3(ne):
    for let in ne:
        print(len(ne[let]))
        print(ne[let],"has",len(ne[let]),"letters.")

Using this code I get a type error "list indices must be integers or slices, not str"

I have played around with the code but everything I try returns the same type error. Im only a couple weeks into python so sorry if this is a dumb question. Help me out guys!! Thanks.

jpp
  • 134,728
  • 29
  • 196
  • 240
  • 1
    `for let in ne:` ... `let` is each _element_ of the list, NOT an index into the list. `print(len(let))` should do ... thanks for a well laid out question – Patrick Artner Nov 27 '18 at 19:31
  • 1
    Look *carefully* at the marked duplicate. When you iterate over a list, you are iterating over the elements themselves. – jpp Nov 27 '18 at 19:31
  • when you do `for let in ne`: `let` is not an index, it's a value in `ne` so first time `let = "Maine"`. I hope this hint is enough for you to solve the problem. You should learn to debug by printing at each step and understanding what is going wrong and where. – Autonomous Nov 27 '18 at 19:33
  • 1
    Hey thanks @Patrick Artner I got what you said about let is an element and not index. I tried your method and it worked on multiple lists. Thanks! – Jadon Murphy Nov 27 '18 at 19:36

0 Answers0