Love Preet Singh
Love Preet Singh

Reputation: 51

Python, removing elements under nested loops from a list

I have written a code to get prime numbers upto a certain limit in a list. As shown above.

import math
 primes = []
 for i in range(1, 101):
     primes.append(i)
 primes.remove(10) # Just removing for sake of experiment
 tot = math.sqrt(len(primes))


for j in range(2, math.ceil(tot), 1):
     for l in range(0, len(primes)):
         k = j**2 + l*j
         primes.remove(k)

primes.remove(12) # Just removing for sake of experiment

print(primes)

This code is showing error while when it removes elements from nested loop. Error is shown above.

Traceback (most recent call last):
   File "/root/PycharmProjects/love/love.py", line 13, in <module>
     primes.remove(k)
 ValueError: list.remove(x): x not in list

Why is this happening as this code was able to remove element which is not under nested loop but was unable to remove element which is being removed under nested loops.

Is there any alternate solution to this problem?

Upvotes: 0

Views: 841

Answers (1)

cosinepenguin
cosinepenguin

Reputation: 1575

You are iterating over a list while you are editing a list, which is something you should never do! When you iterate the list here:

for l in range(0, len(primes)):

You are actually changing the value of len(primes) when you remove the primes! So this causes the code to act irregularly, as:

In the list comprehension, the original list is left intact, instead a new one is created. (SOURCE)

Instead, you can use list comprehension to achieve the same result!

import math
primes = []
for i in range(1, 101):
    primes.append(i)

primeslst = []

def isPrime(number):
    for i in range(2,int(number/2)+1):
        if number%i == 0:
            return True
    return False

primes = [p for p in primes if not isPrime(p)]


print(primes)

Hope it helps!

Upvotes: 1

Related Questions