'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?
Solution 1:[1]
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
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | diu_too_too |
| Solution 2 | Althorion |
