Error:list index out of range
<p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p>

<p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4."</p>

<p>Here is my code which works if I create a list and then run it locally (on codingbat.com it is necessary to create a function but I do not create a function to test my code locally):</p>

<pre><code>arr = [14,9,28,55,66,33,789,4548]

    for i in range (4):

        if arr[i] == 9:

            print('True')

    print('False')*
</code></pre>

<p>Here is the code I'm trying to run on codingbat.com but I receive "Error:list index out of range" error:</p>

<pre><code>def array_front9(arr):

    for i in range(4):

        if arr[i] == 9:

            return True

     return False
</code></pre>

<p>Here is the solution according to codingbat.com:</p>

<pre><code>def array_front9(nums):
  # First figure the end for the loop
      end = len(nums)
          if end &gt; 4:
              end = 4

for i in range(end):  # loop over index [0, 1, 2, 3]
    if nums[i] == 9:
      return True
    return False
</code></pre>

<p>Here is the current URL for this problem: <a href="http://codingbat.com/prob/p110166" rel="nofollow">http://codingbat.com/prob/p110166</a></p>

<p>Can anyone point me to what I'm doing wrong?</p>

<p>It is given in the problem that the array length may be less than 4. Your are just iterating over an array. You should first check whether the <code>array</code> is at least of <code>length 4</code>. If the <code>array</code> is less than 4 then only iterate through the length of the <code>array</code>.</p>

<pre><code>n = 4

if len(arr) &lt; 4:
    n = len(arr)

for i in range(n):
    #...Your code...
</code></pre>

python arrays list