Python One Line for Loop

In our daily life, we often write some big programs and some small level programs to solve the different problems. Whenever we try to solve a complex level problem, then we have to write so many lines of code.

In that code, we often use different types of loops like for, while, or any conditional statements like if, if-else or if-elif-else.

Sometimes we have to write the whole loop to process a single statement in the loop or a minimum of two or three statements. When we write this in our code it generally takes approx 4 to 5 lines to complete a general for loop in which we have to perform a single operation.

Case 1:

For example, I am showing you the code where we are trying to print whole numbers upto 5.

Output:

As we can see in the loop we are only printing the i value, it takes 2 lines to complete the loop and execute it.

If we want to process 2 or 3 statements in a loop, python allows us to do it in a single line only.

It is also called single liners in python. We can use a single line for loop to write the same program in less numbers of spaces. Although sometimes it increases the readability but if you are experienced with it then you will find it useful.

Now let’s see the one liner for the above example.

In the above example, we can see that we have written the same code in a single line only.

These single liners can be useful to quickly write a task in which we simply want to perform one or two operations.

Case 2:

In the above examples, we have seen how to write one liner for loop in which we have to perform a single operation. Now we will see how to write one liner for loop in which we have to perform some complex operations.

Let’s see the example where we are going to use a for loop and we will be using some if else conditions in that loop.

First, we will see how to write it in a traditional way, after that we will see how to write it in one liner way.

Output:

In this example, we are trying to print the square value of i when it is less than 5.

If it is greater than 5 then we simply print 0. As we can see in the example to write code for this problem, we use 6 lines to complete it. But using one liner we can complete it in a single line only.

We will get the same output in both of the cases. In one case we have written the code in 6 lines and in the second case we have written the code in 1 line only.

Although for a beginner I will recommend going with the traditional option only because as a beginner there will be some difficulty in understanding one liner.

Leave a Comment

Your email address will not be published. Required fields are marked *