Avoid running into list out of index error Python

Question:

How can I compare two adjacent elements in an array without running into index out of range error.

I am trying to do something like this:

def count(n):
    counter = 1
    for i in range(len(n)):
        if n[i] == n[i+1]:
            counter += 1
    print(counter, n[i])

I can see that the problem is when it access the last element in n it can no longer find index i+1 and that’s why it generates this error.
but I need to know how to avoid this error while still checking the last element in the array or string( without changing the range to the length of n minus 1.

Asked By: Ruf

||

Answers:

def count(n):
    counter = 1
    for i in range(len(n) - 1):  # changed here
        if n[i] == n[i+1]:
            counter += 1
    print(counter, n[i])

Note that the last element of the list isn’t ignored – it’s compared with the second-to-last lement of the list.


range(len(n)) will generate 0, 1, ..., len(n) - 1. Note that len(n) - 1 is the last index in the list, since lists are zero-indexed.

Similarly, range(len(n) - 1) will generate 0, 1, ..., len(n) - 2.

The last iteration of the loop will have i = len(n) - 2. Note that n[i+1] will access the last element of the list, because len(n) - 2 + 1 == len(n) - 1.

Answered By: Green Cloak Guy

Alternatively you could this simple zip to compare those two adjacent numbers at the same time, and not worrying about index out of bound:

def count_adjacent(nums):
    count = 0
    for a, b in zip(nums, nums[1:]):
        if a == b: count += 1
    return count

>>> 
>>> count_adjacent([1,1,1,2,2,3, 4, 4, 5])
                      ^ ^   ^       ^
4

Second approach to use pairwise

from itertools import pairwise

def count_adj(L):
    return sum(a == b for a, b in pairwise(L))   # more efficient
Answered By: Daniel Hao

Just change

if n[i] == n[i+1]:

to

if (n[i] == n[i+1])& (i!=n):

or

if (n[i] == n[i+1]) and (i!=n):
Answered By: NIKhil kumar
def count(n):
    counter = 1
    for i in range(len(n)):
        for j in range(len(n)):
           if i == j: counter += 1
              
    return counter

or
if the array can be combined to a list, you could use this

   def counter(n):
       count = 0
       for num, num1 in zip(n, n[1:]):
          if num == num1:
            count += 1
          return count
Answered By: temi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.