0
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 ?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I wanted to find prime factors of the number
0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.