user3022573
user3022573

Reputation: 31

Python Error: list index out of range

I keep getting the error list index out of range. I'm not sure what I'm doing wrong.

My code:

from scanner import *

def small(array):
    smallest=array[0]
    for i in range(len(array)):
        if (array[i]<smallest):
            smallest=array[i]
    return smallest

def main():
    s=Scanner("data.txt")
    array=[]
    i=s.readint()
    while i!="":
        array.append(i)
        i=s.readint()
    s.close()
    print("The smallest is", small(array))

main()

The traceback I get:

Traceback (most recent call last):
  File "file.py", line 21, in <module>
    main()
  File "file.py", line 20, in main
    print("The smallest is", small(array))
  File "file.py", line 5, in small
    smallest=array[0]
IndexError: list index out of range

Upvotes: 0

Views: 1466

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1124848

array is empty. There is no array[0] when a list is empty.

You could test for this edgecase, perhaps:

def small(array):
    if not array:
        return None

Upvotes: 5

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

Assuming the first call to .readint() returns "", then your array still is [] after the while loop, and therefore array[0] causes an IndexError.

Upvotes: 2

rdodev
rdodev

Reputation: 3202

Is likely that the array you are passing is empty. For instance, if there's an empty line or empty data in the input file.

Upvotes: 1

Related Questions