Home > Back-end >  How can I avoid index out of range error with enumerating, while comparing each element to its neigh
How can I avoid index out of range error with enumerating, while comparing each element to its neigh

Time:09-21

I have an array that I am looping over and I want to compare each element to the element next to it, and if it is larger say, then I want to do something with its index. It's clear to me that enumeration would help in this case; however I am running into an 'index out of range error':

array = [1,2,3,4]

for index,i in enumerate(array): 
    if array[index]>array[index 1]: 
        ... 

While I know there are other ways of doing this, is there a way I can make the above work with enumerate? I tried to do enumerate(array)-1 ; knowing this would not work. But anything of this sort that would fix the indexing error? Thanks

I know we can easily do the above with simply using 'i' from the for loop, but just curious if I can manipulate enumeration here.

CodePudding user response:

You can just shorten the range:

for i, val in enumerate(array[:-1]): 
    if val > array[i 1]:
        # do stuff

If you don't need the index, you can use zip to the same effect:

for prev, crnt in zip(array, array[1:]):
    if prev > crnt:
        # do stuff not requiring index

The slicing requires O(n) extra space, if you don't want that, you can use your original approach without enumerate, but a simple range:

for i in range(len(array)-1): 
    if array[i] > array[i 1]:
        #  ...

CodePudding user response:

Use zip and slice:

for i, j in zip(array, array[1:]):
    print(f'i: {i} - j: {j}')

Output:

i: 1 - j: 2
i: 2 - j: 3
i: 3 - j: 4

CodePudding user response:

Doing this way will set index at 0 and i at 1. A list is starting at 0 in Python. So at i=3, you are looking at array[i 1]=array[4] which does not exist ! That is why the program is saying 'index out of range error'.

Here is what I suggest if you want to stick with lists:

array = [1,2,3,4]

for i in range(len(array)-1): 
    if array[i]>array[i 1]: 
        ...

If you want to manipulate the index, then it will be the current index in your loop (i). Maybe I have not understood your issue correctly but I suggest you to use numpy if you want to work with array-like objects.

Charles

CodePudding user response:

What logic do you need to apply for the last element in the list?

You can use the range function instead of enumerate.

If you don't need to implement business logic to last element, then use below:

array = [1,2,3,4]

l = len(array)

for i in range(l-1): 
    if array[i]>array[i 1]: 
        ... 

If you do need to implement business logic to last element then use below:

array = [1,2,3,4]

l = len(array)

for i in range(l): 
    if i==l-1:
        implemet last elemt logic
    else:
         if array[i]>array[i 1]:
         ....
  • Related