List Comprehension for Prime NumbersAdmin
What is List Comprehension?
List Comprehension is a smarter way of writing a code whose output was supposed to be a list that was using for loop and may be some if statements. The words “List” + “Comprehension” speak for themselves. We are trying to comprehend whatever was written in such a way that the output that was to be created (a list), can be created in one line. It sounds simple and looks and feels also simple. But may not be always.
The example we are taking today is to create a list comprehension to find out which all numbers from a random set of numbers, are Prime and Not Prime. But before we get that result, let us understand how List Comprehension really works. There’re a few prerequisites for working with lc (hereafter List Comprehension will be referred to as lc).
- Must have at least 1 for loop.
- You cannot use else (except a certain scenario, discussed below).
- The output that you are looking for should be of type list.
Example 1: Multiply every number between 0 to 9 with 2
You see, that the number of lines have been reduced when we make use of list comprehension. The easy way to remember lc is, whatever that comes inside the append method (in Fig. 1) comes as the first value inside the list (in Fig. 2). Following which we write the for loop as it is. If there were any condition(s) after for loop, then they would precede the for. Look at Fig. 3 and Fig. 4 to understand more.
And again you see that the lines of code has been reduced. Another thing to observe is that it is practically impossible to write else part of a lc. In order to get the Odd numbers from the list of random numbers, you have to give else block (Fig. 3). But that is not possible in case of lc (Fig. 4).
We hope this cleared the basic concept of list comprehension. Now coming back to the problem statement, “List Comprehension for Prime Numbers”. The way we would solve this would be using two list comprehensions.
Observe how the inner list comprehension is used to find if a number (i) is divisible by any number between 2 and half of that number (i). If yes, then we add ‘NotPrime’ in the inner list.. Else the list remains empty. The outer list comprehension checks if the string ‘NotPrime’ is not available in inner list. In which case the number is a Prime number.
How do you think you can find the “Not Prime number” using list comprehension? It’s very simple. Just change “if NotPrime in” to “if NotPrime not in”. Check Fig. 6 for code.