Im trying to pass a list of numbers to a primality function. What I expect is for it to return the items that are primes and discard those that arent.
Here is the code:
def primality(num):
if num % 2 == 0 and num > 2:
return False
return all(num % i for i in range(3, int(math.sqrt(num)) + 1, 2))
Does not work, why?
nums = [31, 71, 91, 32, 92, 13, 73, 14, 34, 74]
for i, s in enumerate(nums):
if not primality(nums[i]):
del nums[i]
print(nums) # it prints [31, 71, 32, 13, 73, 34] which is wrong, 32 and 34 shouldnt be there
But this works:
temp = []
for i, s in enumerate(nums):
if not primality(nums[i]):
continue
temp.append(s)
print(temp) # [31, 71, 13, 73] which is correct
My question is very basic, but I cant figure out why the first method of removing items from the existing list doesn't remove all non-primes? what am I doing wrong?