Jatinshravan
Jatinshravan

Reputation: 445

String index out of range error python

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?

Upvotes: 0

Views: 954

Answers (4)

pondohva
pondohva

Reputation: 113

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

Upvotes: 0

Archit Jain
Archit Jain

Reputation: 2234

You may want to add :

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

Upvotes: 1

falsetru
falsetru

Reputation: 369054

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

Upvotes: 3

kevinsa5
kevinsa5

Reputation: 3411

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.

Upvotes: 3

Related Questions