Anik Patra
Anik Patra

Reputation: 21

Getting an error: list assignment index out of range

I am getting an error list assignment index out of range in the following code:

n=input("How many numbers?\n")
print "Enter ",n," numbers..."
a=[]
for i in range(0,n):
    a[i]=input()

elem=input("Enter the element to be searched: ")

for i in range(0,n):
    if a[i]==elem:
        flag=1
        break

if flag==1:
    print "Item is present in the list"
else:
    print "Item is not present in the list"

Upvotes: 2

Views: 116

Answers (3)

Abhishek Gurjar
Abhishek Gurjar

Reputation: 7476

Use it like this,

n=input("How many numbers?\n")
print "Enter ",n," numbers..."
# assigning with n times zero values which will get overwritten when you input values.
a=[0]*n
for i in range(0,n):
    a[i]=input()

elem=input("Enter the element to be searched: ")

for i in range(0,n):
    if a[i]==elem:
        flag=1
        break

if flag==1:
    print "Item is present in the list"
else:
    print "Item is not present in the list"

Upvotes: 0

Mikael
Mikael

Reputation: 554

You're setting a list index without it declaring. See:

a=[]

Then you want to access some index?And you're reading a string with input,convert it before using. Things will look like:

n = int(n)
a= []*n

Upvotes: 0

brennan
brennan

Reputation: 3493

Adding some type safety with int, using list method append and operator in:

n = input("How many numbers?\n")
n = int(n)
print "Enter ", n, " numbers..."
a = []
for i in range(n):
    x = input()
    a.append(x)

elem = input("Enter the element to be searched: ")

if elem in a:
    print "Item is present in the list"
else:
    print "Item is not present in the list"

Upvotes: 1

Related Questions