Home > Software engineering >  Python IndexError out of range after using for loop with range(len(list[:])-1)
Python IndexError out of range after using for loop with range(len(list[:])-1)

Time:03-11

I keep running into an error that is saying that my index is out of bounds at line (19). However I have added conditions making it so that it couldn't be out of bounds if it followed through with the loop. I am unsure why I keep getting this python error.

Here is a rough version of the code I am using:

df = pd.read_csv('some_csv.csv', sep=" ")
new_list = df.values.tolist()

for i in range(len(new_list[:]) - 1):
  if new_list[i][2] == new_list[i 1][2]:
      do some property
  else:
      do something different

However I keep encountering the error:

Traceback (most recent call last):
 File "PVE.py", line 18
    if new_list[I][2] == new_list[I 1][2]
IndexError: list index out of range

I shouldn't be out of range, since I am telling it to be literally -1 off the top of the range, to account for the 1 it is comparing it to. Why am I encountering this error? How can I fix this?

CodePudding user response:

It looks like is because of

for i in range(len(new_list[:]) - 1):

for loop by default iterates -1 len so you are interating -2. In that case try this

for i in range(len(new_list):

CodePudding user response:

As I said in my comment, you have only 2 columns in your dataframe, so the third index ([2]) is out of range.

You can use this code which is equivalent to your loop:

import numpy as np

np.where(df['col2'] == df['col2'].shift(-1), "do some property", "do something different")
  • Related