How does this work? [Python List Comprehension] | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How does this work? [Python List Comprehension]

# below list contains prime and non-prime in range 1 to 50 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] print primes How does noprime work here?

8th Jun 2019, 5:45 AM
Code Ninja
Code Ninja - avatar
2 Answers
+ 4
If you want a non-prime number, you don't need to divide it with numbers bigger than 8 (since all the numbers divisible by 9 can be divisible by 3...). The second for loop checks all of the multiples of that number below 50. The numbers that aren't on the list, are considered prime numbers.
8th Jun 2019, 6:02 AM
Airree
Airree - avatar
+ 3
The code is fairly nice, so I did some trials with it. It’s a really good idea to use list comprehension here. I do not want to question anything here or criticize anything. Using just the code as it is has no problems. A critical point is if you change the upper limit from 50 to (let’s say) 10000. This leads to some numbers in the result of primes that are no primes at all. So you should be aware that a change of the upper limit from 50 to 10000 needs also a change in upper limit for noprimes from 8 to the square root of “upper limit”. The square root value is 100. So it would be a good idea to modify the code to this version: lim = 10000 noprimes = [j for i in range(2, int(lim**0.5)+1) for j in range(i*2, lim,i)] primes = [x for x in range(2, lim) if x not in noprimes] print(primes) Another possible way is to use sqrt from math module because execution time is a little faster than **0.5. In general the code is not the fastest. Calculating primes over 100000 takes too much time compared to other codes I have tested.
8th Jun 2019, 12:27 PM
Lothar
Lothar - avatar