简体   繁体   中英

ValueError: list.remove(x): x not in list in Python

This is my code

lower = int(input('pleace input the beggest num:'))
upper = int(input('pleace input the smallest num:'))
lis=[]
for num in range(lower,upper):
    lis.append(num)
    for i in range(2,num-1):
        if num%i == 0:
            lis.remove(num) 
print(lis)

Which stop is wrong?

I guess this programme is to find all primes between [lower, upper). And the problem in your code is that you should break the loop when you find x is not prime. such as:

if num%i == 0:
    lis.remove(num)
    break

If there is a number that's divisible by more than one number from range(2,num-1) , your program will try to remove it multiple times, but that value wouldn't be there after it's removed the first time.

For example, let's consider number 6. You add it to your list, then, in the for loop, you go from 2 to 4 (mind you, range excludes the upper limit.). 6 % 2 == 0 , so your if statement is true, so you remove that six from the list… but the loop continues. Then, it checks for 3, and 6 % 3 == 0 , too, so it tries to call lis.remove(6) … but that six is no longer there—you've removed it beforehand.

In the future, consider using a debugger for running your programs step-by-step, it will help you find your errors.

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