I am practicing list comprehensions and nested list comprehensions. As part of my practice I am writing out equivalent for loops. This for loop I cannot get right, and I believe it's because I'm trying to assign a value rather than a variable in a function call. The error I receive is:
File "<stdin>", line 4
SyntaxError: can't assign to function call
The code I have written for this loop is:
import math
def squared_primes():
list = []
for x in range(1,1000000):
for q in range(2,math.sqrt(x)+1):
if all(x % q != 0):
list.append(x**2)
print(list)
This function is trying to create a list of perfect squares whose roots are prime numbers in the range 1 to 1000000.
Can someone help me understand where exactly the syntax of my loop breaks down? Also, can I possibly do this as a nested list comprehension? Clearly my list comprehension is breaking down because I can't get my for loop syntax right...
SOLUTION: Thanks to user @Evan, I was able to fix the variable and syntax problems, and took some cues about how to fix the all()
statement from this thread.
This code will properly return a list of the squared primes from 1,1000:
def squared_primes():
list1 = []
for x in range(1,1000):
if all(x%q !=0 for q in range(2,int(math.sqrt(x)+1))):
list1.append(x**2)
print(list1)