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
Creating an array with zeroes
Selecting the even numbers in a range
One-liner for if-else statements
Manipulating an array
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.
Top comments (6)
You shouldn't be. Loops are notorious for being slow due to the iterator being accessed and manipulated. You have just discovered in Python what we've known in Perl for years: less code is faster. We use
map
andgrep
liberally in Perl and then get accused of being "too clever". Welcome to reality!Thanks for the informative reply Mr. Matthew
Why in the second example do u use a true if x else false
X is a boolean expression so just type that ^^
yeah Thanks for that. I have not noticed it.
Yeah it depends.i totally agree with your point
Time taken for the execution in seconds