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>The problem is in the line 18</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"))
print(s)
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: &lt;-- here
        j+=1
        i=0
</code></pre>

<p>At some point, your <code>i = 5</code> and <code>j = 4</code>, so the right side of this <code>if i == 5 and j &lt; 4</code> statement is being False, and the <code>i</code> is not reseted to 0. So at the next loop, the <code>i</code> is equal to 5, and the maximum index is 4.</p>

<p>Better solution would be to use for loops.</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"))
for i in range(len(s)):
   for j in range(len(s)):
       if s[i] in s[j]:
          print("\"" + s[i] + "\" is in the string \"" + s[j] + "\"")
</code></pre>

<h1>Edit to answer comment</h1>

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

python python-3.x indexing