Do Python One-Liners Make Your Code Faster?

naveenkumarmd

Naveenkumar M

Posted on November 17, 2021

Do Python One-Liners Make Your Code Faster?

Most Python programmers have a myth that one-liners are the best way of programming and they even think that one-liners make the code faster. Let us check out this thing and analyze how one-liners differ from normal codes.

Let us consider some of the five programs

  1. Creating an array with zeroes

  2. Selecting the even numbers in a range

  3. One-liner for if-else statements

  4. Manipulating an array

  5. Checking palindrome

We will be using the “time” module to check the time taken to execute the program.

1. Creating an array with zeroes

Let us create a 2-dimensional array of zeroes with a normal iterative method and let’s note the running time.

Time taken is: 12.876641988754272

I have run this program several times and found the maximum value So that we can analyze it easily.

Let us check the one-liner for doing this.

Time taken is: 4.390255928039551

2. Selecting the even numbers in a range

This time I wish to make the time a notable one. So I iterated the loop 99999999 times. The program is quite simple if the number is even I will append it in the array else nothing will happen.

Time taken is: 21.109660625457764

One-liner

Time taken is: 9.88336968421936

3. One liner if-else with a function

Let us find the count of multiples of 3 in a range.

Time taken is: 139.78343963623047

Let us convert the divisibleby3 function and the main function to one-liners to compare the results.You can even convert the divisibleby3 function into a lambda function to make it even complex.

Time taken is: 56.80164098739624

4. Manipulating an array

Let us convert the array of elements to its square values.

Time taken is: 56.80164098739624

Time taken is: 39.76653861999512

5. Palindrome check

This is a function to check whether a number is a palindrome or not.

Time taken is: 16.703513860702515

One liner:

Time taken is: 0.16199564933776855

I’m astonished by the above results.

From the above table it is clear that the one liners make the code much faster. It will help you in competitive programming and so on.

💖 💪 🙅 🚩
naveenkumarmd
Naveenkumar M

Posted on November 17, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related