Home > Software design >  list index out of range (notcars[5])?
list index out of range (notcars[5])?

Time:10-25

Probably a noob question but getting this error list index out of range when running.

images = glob.glob('/OwnCollection')

cars = []
notcars = []
all_cars = []
all_notcars = []

for image in images:
    if 'non-vehicles' in image:
        all_notcars.append(image)
    else:
        all_cars.append(image)

# Get only 1/5 of the training data to avoid overfitting
for ix, notcar in enumerate(all_notcars):
    if ix % 5 == 0:
        notcars.append(notcar)
        
for ix, car in enumerate(all_cars):
    if ix % 5 == 0:
        cars.append(car)
        
car_image = mpimg.imread(cars[1])
notcar_image = mpimg.imread(notcars[5])

Error code

---> 24 car_image = mpimg.imread(cars[1])
     25 notcar_image = mpimg.imread(notcars[5])
     26 

IndexError: list index out of range

inside of the folder has two folders named "non-vehicles" and the second named "vehicles"

any help is highly appreciated.

CodePudding user response:

your code command get arrays in number 1 and 5 like this

car_image = mpimg.imread(cars[1])
notcar_image = mpimg.imread(notcars[5])

but in this program have an array less than 1 in cars, so you must know how long your array with the command

print(len(cars))

and your array command less than long array

CodePudding user response:

The error “list index out of range” arises if you access invalid indices in your Python list. In other words if yo have one variable saved it would be stored in the first cell of a array

Array example

so your code might need to go something like this

car_image = mpimg.imread(cars[0])

Maybe a double check where your image is could be useful, this could trough out a error of index if it doesn't find anything

  • Related