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>Thank you for all your answers, they have been really helpful!</p>

<p>I decided to use the IF loop instead of the FOR loop, like this:</p>

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

    if 9 in arr[0:4]:

        return True

    return False
</code></pre>

<p>As much as I can see, this solution works no matter what the length of the list is, and it seems like it fits the definition of the problem i.e. "no matter what the length of the list is, if any of the first four elements equals 9, return True". </p>

python arrays list