-2
b=[2, 3, 0, 5, 0, 7, 0, 0, 0, 11, 0, 13, 0, 0, 0, 17, 0, 19, 0, 0, 0, 23, 0, 0, 0, 0, 0, 29, 0, 31, 0, 0, 0, 0, 0, 37, 0, 0, 0, 41, 0, 43, 0, 0, 0, 47, 0, 0, 0, 0, 0, 53, 0, 0, 0, 0, 0, 59, 0, 61, 0, 0, 0, 0, 0, 67, 0, 0, 0, 71, 0, 73, 0, 0, 0, 0, 0, 79, 0, 0, 0, 83, 0, 0, 0, 0, 0, 89, 0, 0, 0, 0, 0, 0, 0, 97, 0, 0, 0] 
#b is a list of primes with composite numbers turned into zero!
#code to remove zeroes
for k in b:
    if k==0:
        del k
print(b)

I'm welcome to any suggestions that are reasonably simple since I'm a beginner and self-taught. If there's anything I'm doing horribly wrong, please do point that out as well. Thank You

1 Answers1

0

I would use list comprehension to remove all occurences of 0:

b=[2, 3, 0, 5, 0, 7, 0, 0, 0, 11, 0, 13, 0, 0, 0, 17, 0, 19, 0, 0, 0, 23, 0, 0, 0, 0, 0, 29, 0, 31, 0, 0, 0, 0, 0, 37, 0, 0, 0, 41, 0, 43, 0, 0, 0, 47, 0, 0, 0, 0, 0, 53, 0, 0, 0, 0, 0, 59, 0, 61, 0, 0, 0, 0, 0, 67, 0, 0, 0, 71, 0, 73, 0, 0, 0, 0, 0, 79, 0, 0, 0, 83, 0, 0, 0, 0, 0, 89, 0, 0, 0, 0, 0, 0, 0, 97, 0, 0, 0] 
#b is a list of primes with composite numbers turned into zero!
# Iterates through all the values and returns them unless they are 0
b = [x for x in b if not x == 0]
print(b)
  • Thank you! In my above code , why is the line ' del k ' is not read by the interpreter?@ Kyle Wang – Jayasri Palanisamy Aug 28 '20 at 05:56
  • think of k like a different variable that is not part of b. Deleting it will just delete the reference to the value of x[n], where n is the index of k. So, say you wanted to perform an operation on k, then what? I, personally would use list comprehension for small things as it is easy to read, but for more complicated things you can make a new empty liist and use a for loop to perform an operation to k and then append it to your new variable. – Impossible Reality Aug 30 '20 at 09:48