收到错误:列表分配索引超出范围

时间:2017-04-04 16:38:32

标签: python python-2.7 list

我在以下代码中得到的错误列表分配索引超出范围:

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"

3 个答案:

答案 0 :(得分:1)

使用 int 添加一些类型安全性,使用追加中的运算符

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"

答案 1 :(得分:0)

您在没有声明的情况下设置列表索引。参见:

a=[]

然后你想要访问某个索引?你正在读取带有输入的字符串,在使用之前将其转换。事情看起来像:

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

答案 2 :(得分:0)

像这样使用,

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"