Home > Software engineering >  Python ValueError: list.remove(x): x not in list error
Python ValueError: list.remove(x): x not in list error

Time:09-18

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)

CodePudding user response:

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.

CodePudding user response:

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)]
  • Related