Loop prime number list to 100 python

broken image
broken image

In side the condition if which is optional predicate. This is the syntax of list comprehension.

broken image

It sometimes happens to me too, in your case, the for y in range(2,int(x/2)+1) works as a normal for loop. However, you need comprehend it in order to utilize the list comprehension well. Coincidentally, list is just all about list comprehension. Your code written in for loop would be like this: for x in range(5,20):īecause any requires an iterable such as a generator expression or a **list** as mentioned above by. Your code is wrong because you inherit too much from the ordinary for loop.

Both of the above approaches have a time complexity of O (n). As the only factor of n greater than n/2 is n itself, you may choose to run only up to n/2. If you don’t find a factor that divides n, then n is prime. You can simply understand that the loop comprehension already have the list of values, then they just simply feed orderly to the condition value by value. To check if a number is prime, the naïve approach is to loop through all numbers in the range (2, n-1). You may find out that the result of list comprehension is always a list, meanwhile the result of for loop would always many single values and these single values is a part of iterable That is just the wonderful thing about list comprehension if it can work normally like the for loop, people wont create it because the for loop is more readable and understandable.

broken image