user6912880 user6912880 - 2 months ago 8
Python Question

Python: List index out of range though appearing not to be

I wrote a simple program to check if strings are substrings of eachother. The issue is I keep getting a list index out of bounds error.

I tried printing i and j with each iteration and they never go out of the bounds of the list. I even tried to insert elements at s[5] and s[6] to check the index but still get the same error. What could be the cause of this error?

s = []
s.insert(0,str("a b c"))
s.insert(1,str("a b c d"))
s.insert(2,str("a b"))
s.insert(3,str("b c"))
s.insert(4,str("d"))

j = 0
i = 0

while j < 5:
if s[j] in s[i]:
print("\"" + s[j] + "\" is in the string \"" + s[i] + "\"")
i +=1
if i == 5 and j < 4:
j+=1
i=0


This is my console output

Traceback (most recent call last):
"a b c" is in the string "a b c"
File "C:/Users/Kal/PycharmProjects/untitled/FSS2.py", line 16, in <module>
"a b c" is in the string "a b c d"
if s[j] in s[i]:
"a b c d" is in the string "a b c d"
IndexError: list index out of range
"a b" is in the string "a b c"
"a b" is in the string "a b c d"
"a b" is in the string "a b"
"b c" is in the string "a b c"
"b c" is in the string "a b c d"
"b c" is in the string "b c"
"d" is in the string "a b c d"
"d" is in the string "d"

Process finished with exit code 1

Answer

At the point when your code is raising the exception, the value of i is 5 and the value of j is 4. In your print statement you try to do s[i] i.e. s[5]and since max index of s is 4, your code is raising IndexError.

I believe, in your code you need to do make modification in your if statement as:

if i == 5 and j < 5:  # Instead of j < 4

Then your code runs fine:

>>> while j < 5:
...     if s[j] in s[i]:
...         print("\"" + s[j] + "\" is in the string \"" + s[i] + "\"")
...     i +=1
...     if i == 5 and j < 5:
...         j+=1
...         i=0
... 
"a b c" is in the string "a b c"
"a b c" is in the string "a b c d"
"a b c d" is in the string "a b c d"
"a b" is in the string "a b c"
"a b" is in the string "a b c d"
"a b" is in the string "a b"
"b c" is in the string "a b c"
"b c" is in the string "a b c d"
"b c" is in the string "b c"
"d" is in the string "a b c d"
"d" is in the string "d"
Comments