Home > Back-end >  Avoid running into list out of index error Python [duplicate]
Avoid running into list out of index error Python [duplicate]

Time:09-21

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.

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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):
  • Related