0

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
5
  • Can you show us the full traceback please? Commented Nov 22, 2013 at 16:41
  • Please edit your post to include the full traceback. Commented Nov 22, 2013 at 16:41
  • 1
    You're probably passing an empty array to the small() function.. consider adding error handling for that! Commented Nov 22, 2013 at 16:41
  • 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 Commented Nov 22, 2013 at 16:57
  • @user3022573: Next time, edit your question to add the traceback. I've added it in for you. Commented Nov 22, 2013 at 17:07

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.