简体   繁体   中英

List Index out of range error. Python

lst = []
for i in range(1,13196):
    if 13195 % i == 0:
        lst.append(i)
for k in range(len(lst)):
    for j in range(1,lst[k]):
        if lst[k] % j != 0:
            lst.remove(lst[k])
print(lst)

When I run this code, it says if lst[k] % j != 0: List index out of range . Can anyone tell me what I did wrong ?

You are iterating over a range of the current length of lst . Every time you do lst.remove(lst[k]) , the lst gets shorter, so the range you were using becomes unsuitable. For example, if you start with 8 elements, it goes from indices of 0 to 7 inclusive, but if you remove an element, the last index will then be 6 , not 7 .

The easiest way to fix this is to simply create a new list :

lst = []
for i in range(1,13196):
    if 13195 % i == 0:
        lst.append(i)

result = lst[:] # create a copy to work with
for k in range(len(lst)):
    for j in range(1,lst[k]):
        if lst[k] % j != 0 and lst[k] in result: # check that it's there before removal
            result.remove(lst[k])

print(result)

That said, this code eliminates every number which cannot be evenly divided by every positive integer smaller than that number, which understandably produces a result of [1] . If that's not what you wanted, you'll have to take another look at your algorithm.

lst = []
lst2 = []
for i in range(1,13196):
    if 13195 % i == 0:
        lst.append(i)
        lst2.append(i)

for k in range(len(lst)):
    for j in range(1,lst[k]):
        if lst[k] % j != 0: 
            lst2.remove(lst[k])

print lst2

Give this a try. Your problem is that you were iterating over the value of the original list. When you removed parts of the original list, the length of this value shortened, but the for loop will not account for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM