List index out of range though appearing not to be
<p>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.</p>

<p>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?</p>

<pre><code>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 &lt; 5:
    if s[j] in s[i]:
        print("\"" + s[j] + "\" is in the string \"" + s[i] + "\"")
    i +=1
    if i == 5 and j &lt; 4:
        j+=1
        i=0
</code></pre>

<p>This is my console output</p>

<pre><code>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 &lt;module&gt;
"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
</code></pre>

<p>Keeping your form it would be:</p>

<pre><code>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 &lt; 5:
    if s[j] in s[i]:
        print("\"" + s[j] + "\" is in the string \"" + s[i] + "\"")
    i +=1
    if i == 5 and j &lt;= 4:
        j+=1
        i=0
</code></pre>

<p>The error is in the 2nd if in your <code>while</code> loop. It should be <code>j &lt;= 4</code> or <code>j &lt; 5</code> in order to work.</p>

python python-3.x indexing