Search code examples
pythonalgorithmindex-errorlinear-search

how do i solve index error in linear search algorithm?


n = int(input("Enter size of array"))
num = int(input("Enter numbers"))
for i in range(0, n):
    num = int(input(hello.append(num)))
print(hello)
x = int(input("enter number to check!"))
count = 0
while count <= len(hello):
    if (hello[count]==x):
        print("found")
        break
    elif (hello[count]!=x):
        count = count + 1
    else:
        print("not found")
        break

Hello friends, I am a DSA Beginner and I got an error in my code on linear search. If I enter element which is present in list the code executes but if i enter element which is not present it gives me

"if (hello[count]==x): Index Error: list index out of range"

help me out how my code can be efficient. TNX


Solution

  • If you take a length of a list it gives you the total number of elements in that list. But if you want element of that list with index as the total number of element then it will give out of range error.

    For example :

    $ l = [3,5,4,7,6]

    $len(l)

    5

    $l[5]

    IndexError: list index out of range