It would take quite a few lines of code to accomplish this normally.

noprimes = [] for i in range(2, 8): for j in range(i*2, 50, i): noprimes.append(j) primes = [] for x in range(2, 50): if x not in noprimes: primes.append(x)

However, you can simplify this by using two list comprehensions.

noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)] primes = [x for x in range(2, 50) if x not in noprimes]

The first line uses multiple for loops within one list comprehension. The first for loop is the outer loop, and the second for loop is the inner loop. To find primes, we are first finding a list of non prime numbers. This list is generated by finding multiples of numbers 2-7. Then we loop through a range of numbers and check to see if each number is in the list of non primes.

Edit: as pointed out by shoyer on reddit, using a set for finding noprimes is much more efficient. Since noprimes should contain only unique values and we frequently have to check for the existence of a value, we should be using a set. Set comprehension has similar syntax to list comprehension so we can use the following: