Search code examples
pythonsearchlinear-search

IndexError: list index out of range in array search


I'm making a simple program in Python to perform a linear search. But when I run this program it gives me this error:

Traceback (most recent call last):
  File "C:\Users\raj\Documents\EclipseProject\PythonProject1\myProgram.py", line 25, in <module>
    if array[myNumber] == search:
IndexError: list index out of range

Here is my program:

array = []

numCase = input("Enter your number cases: ")

numCase = int(numCase)
array = [numCase]

print("Enter the number with", numCase, "times.")

for i in range(0, numCase):
    myNumber = input()
    myNumber = int(myNumber)
    array = [myNumber]

print("Enter the values which you're looking for: ")
search = input()
search = int(search)

for c in range(0, numCase):
    if array[myNumber] == search:
        print(search, "is present at", (c+1))
        break

# If number is absent!!
if c == numCase:
    print(search, "is not present!!")

Solution

  • Your current issue is this line

    array = [myNumber]
    

    All that you are doing is setting array to be a list of 1 element repeatedly with this line, as opposed to adding each element to array. Use the increment operator += instead, so that you are actually adding each element to array:

    array += [myNumber]
    

    As a much more idiomatic alternative, it looks as though you are prompting the user to input the same number 'x' times. As mentioned by TheBlackCat you could simply build array with

    array = list(range(numCase))
    

    if this is in fact what you are attempting to do.

    Additionally, you should be using c as your array index as it is what you are iterating over.