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><code>randint</code> does not act like the rest of Python (for historical reasons relating to other computer languages). In particular, <code>randint()</code> <em>does</em> include the upper bound, unlike Python's list indices and <code>len()</code>.</p>

<p>So use <code>randint(0,len(self.AI_Greeted) - 1)</code>.</p>

python python-3.x random