0

I'm just beginning with python and I have to define a function to check how many strings in a list have more than 2 characters or have their first and last characters same:

def match_ends(words):
  count=0
  for w in words:
    if len(w)>=2:
      count+=1
    elif w[0]==w[-1]:
      count+=1
  return count

I get an error message saying:

elif w[0]==w[-1]:
IndexError: string index out of range

What does this mean and how do I correct it?

4 Answers 4

3

by writing elif w[0]==w[-1]:, you're indexing from the end-- the last element, in other words. Perhaps it's an empty string, so there is no last element to reference? Try printing the strings as you go so you can see what's going on.

Sign up to request clarification or add additional context in comments.

Comments

3

You should check whether w is empty string.

>>> w = ''
>>> w[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

Comments

1

You may want to add :

elif len(w)>0 and w[0]==w[-1]:

Comments

0

In you elif case you catch words with len<2 and get the error. Problem in formulation of the problem, I think.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.