CodingBat has22 why is this solution wrong?
<pre><code>def has22(nums):
  if nums[len(nums) - 1] == 2:
    if nums[len(nums) - 2] == 2:
      return True
  else:
    for n in range(len(nums) - 3):
      if nums[n] == 2 :
        if nums[n + 1] == 2:
          return True
      else:
        return False
</code></pre>

<p>I need to return True if the array contains a 2 next to a 2 somewhere. But it gives me an error that says:"list index out of range". What should i change?</p>

<p>I'm pretty new to the stuff, so probably my code is one of the longest ways to solve it, but i appreciate any help. Thank you!</p>

<p>I think the error you report can only happen if <code>nums</code> is an empty list. In that situation, <code>nums[len(nums) - 1]</code> is not a valid index (as there are no valid indexes into an empty list).</p>

<p>For this problem, there's really not much point to special casing the last two items in the list. You can make your code much simpler by handling all the cases with one loop:</p>

<pre><code>def has22(nums):
    for n in range(len(nums) - 1):   # the loop body will not run if len(nums) &lt; 2
        if nums[n] == nums[n + 1] == 2:   # you can chain comparison operators
            return True
    return False   # this is at top level (after the loop), not an `else` clause of the if
</code></pre>

<p>As the comment says, the loop body where I use list indexes won't run if the length of the list is less than 2. That's because the <code>range</code> will be empty, and iterating on an empty sequence does nothing.</p>

<p>A slightly fancier approach would be to use <code>zip</code> on two iterators of <code>num</code> that are offset by one place. This is more advanced Python stuff, so if you don't understand it yet, don't worry too much about it:</p>

<pre><code>def has22_fancy(nums):
    iters = [iter(nums), iter(nums)]
    next(iters[1], None)
    return any(a == b == 2 for a, b in zip(*iters))
</code></pre>

<p>This approach to iterating over pairs using <code>zip</code> is inspired by the <a href="https://docs.python.org/3/library/itertools.html#itertools-recipes" rel="nofollow"><code>itertools</code> documentation</a>, where it's given in the <code>pairwise</code> recipe:</p>

<pre><code>def pairwise(iterable):
    "s -&gt; (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)
</code></pre>

python