简体   繁体   中英

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

I'm a beginner and I wrote a code that the computer takes some numbers as a list and removes compound numbers and keeps prime numbers then prints the list. It doesn't work with numbers greater than 5 and gives ValueError: list.remove(x): x not in list error.

a=list(map(int,input('Enter some numbers:').split()))
for i in range(0,len(a)):
    b=a[i]
    for j in range(2,b):
        if b%j==0:
            a.remove(b)
        else:
            pass
else:
    print('The prime numbers are:',a)

The immediate problem is that the removal loop:

for j in range(2,b):
    if b%j==0:
        a.remove(b)
    else:
        pass

will continue running even after the element is removed, so for b = 6 , it will attempt to remove 6 twice: once for j = 2 and again for j = 3 . You can solve it by adding a break after the a.remove line.

You also don't need an else clause if there's nothing to be done there, so the last two lines of the loop can be removed, and you'll also likely have issues with i going out of range since you're modifying the list a during the loop.

Modifying a list while iterating over it is not a good idea.

Instead, create a new list containing the prime numbers.

def isprime(x):
  for i in range(2, math.ceil(math.sqrt(x)) + 1):
    if x % i == 0:
      return False
  return True

a = list(map(int, input('Enter some numbers:').split()))

b = [x for x in a if isprime(x)]

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