Python Forum
I'm getting a String index out of range error
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I'm getting a String index out of range error
#1
This function returns True if the first letter of the string is the same as the last letter of the string and False if they’re different.

I'm having trouble explaining why I have the following error with this code:

def first_and_last(message):
    if message[0] == message[-1]:
        return True
    return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
Error:
Error on line 2: if message[0] == message[-1]: IndexError: string index out of range
But if I just add a logical operator it doesn't have an error, my question is why? if both are basically the same, I think the same error should pop out because I'm not doing anything special to specify any input for the second one.

def first_and_last(message):
    if message == "" or message[0] == message[-1]:
        return True
    return False

print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
Output:
True False
Thanks for reading.
Reply
#2
Very strange. Your code (the first code block) works fine for me (Linux OS running Python 3.6.9).

The only thing I'd alter (not that it changes the operation on my system), is to have an 'else' clause in the 'if' branch.

def first_and_last(message):
    if message[0] == message[-1]:
        return True
    else:
        return False
I'm old school and as such I don't like to see an 'if' branch without an 'else' clause.
debian77 likes this post
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#3
>>> message = 'a'
>>> message[0]
'a'
>>> message[-1]
'a'
>>> message = ""
>>> message[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> message[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
if message == "" or message[0] == message[-1]:
in this example, the message == "" would test True, so conditional would be satisfied, and is done at that point.
debian77 likes this post
Reply
#4
One example
def f_and_l(msg):
    if msg[0] == msg[-1:]:
        return True
    return False

print(f_and_l('else'))
print(f_and_l('tree'))
Output:
True False
debian77 likes this post
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#5
Why use True or False when the if statement evaluates to True or False?

I can see no reason you should get an index error for the provided test cases. I think the test for an empty string is a good improvement, but it is not needed for "tree" or "else". Cannot explain how you got the error, but it is not from the code you posted.
ndc85430 and debian77 like this post
Reply
#6
Thank you, everyone. It was my fault, there was a final print function with an "" parameter at the end.
print(first_and_last(""))
So, I think that was the error.
Reply
#7
(Jun-26-2022, 03:53 AM)debian77 Wrote: Thank you, everyone. It was my fault, there was a final print function with an "" parameter at the end.
print(first_and_last(""))
So, I think that was the error.

Easy done.

To mitigate the error, you could test for an empty string at the beginning of your function...

def first_and_last(message):
    if message:
        if message[0] == message[-1]:
            return True
        else:
            return False
    else:
        return False
... which will return 'False' if an empty string is passed to the function.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#8
If and else need not apply.
def first_and_last(message):
    return message == "" or message[0] == message[-1]
ndc85430 and rob101 like this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  pyscript index error while calling input from html form pyscript_dude 2 968 May-21-2023, 08:17 AM
Last Post: snippsat
  Index error help MRsquared 1 761 May-15-2023, 03:28 PM
Last Post: buran
Thumbs Down I hate "List index out of range" Melen 20 3,295 May-14-2023, 06:43 AM
Last Post: deanhystad
Exclamation IndexError: Replacement index 2 out of range for positional args tuple - help? MrKnd94 2 6,277 Oct-14-2022, 09:57 PM
Last Post: MrKnd94
  IndexError: list index out of range dolac 4 1,893 Jul-25-2022, 03:42 PM
Last Post: deanhystad
  IndexError: list index out of range Anldra12 2 1,432 May-03-2022, 01:39 PM
Last Post: Anldra12
  matplotlib x axis range goes over the set range Pedroski55 5 3,165 Nov-21-2021, 08:40 AM
Last Post: paul18fr
  IndexError: list index out of range rf_kartal 6 2,823 Sep-07-2021, 02:36 PM
Last Post: Larz60+
  Python Error List Index Out of Range abhi1vaishnav 3 2,286 Sep-03-2021, 08:40 PM
Last Post: abhi1vaishnav
  Index error - columns vs non-column Vinny 3 4,910 Aug-09-2021, 04:46 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020