Why does list index go out of range when using random module?
<p>I am building a Chatbot and I was able to make it answer to me randomly. I added all the responses in a list and whenever I greet it, It shoots me a random answer. Now this is fine, but sometimes, the program throws an exception - <code>IndexError: list index out of range</code>. I don't understand why the list index is going out of range. The list has 6 items, and by using <code>random.randint(0,len(slist))</code> I was able to get a random response.</p>

<p>I have used exception handling to fix this problem. But, I want to know why it gives an error. </p>

<p>Here's the code without exception handling: </p>

<pre><code>if self.Has_user_greeted == False:
    self.AI_Greet()
 else:
    # goes out of range here
    self.AI_respond = random.randint(0,len(self.AI_Greeted))
    print(self.AI_Greeted[self.AI_respond])
</code></pre>

<p>That is because list indexes start at <code>0</code> and <code>randint</code> will choose a number in the range you specify <code>inclusively</code> with the upper bound. Observe this example: </p>

<pre><code>&gt;&gt;&gt; a = [1,2,3]
&gt;&gt;&gt; len(a)
3
</code></pre>

<p>So, now try to get the value at index <code>3</code>:</p>

<pre><code>&gt;&gt;&gt; a[3]
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
IndexError: list index out of range
</code></pre>

<p>Because the highest index is actually <code>2</code>. </p>

<p>What you want to do in your example is simply <code>-1</code> the length: </p>

<pre><code>random.randint(0,len(self.AI_Greeted) - 1)
</code></pre>

python python-3.x random