10 Most Needed Python Shorthands

Thank me later for these useful one-liners

A block of code is summarized and expressed in one line through an efficient program known as python one-liner. If you publish the coding practice through Python one-liner, it will help you read and write code more concisely.

We will discuss the Python one-liner through a few examples. So let’s get started.

Random Password Generator

A random password generator is a software program that takes random values or digits as input and automatically generates it as a password.

Usual Solution

Shorthand

Check Palindrome

A palindrome is a special word or number that, when read from the beginning of the end, does not change the pronunciation and meaning of the word, or the value of the number remains the same.

Usual Solution

#general
n = input("Enter the word and see if it is palindrome: ")  # check palindrome
if n == n[::-1]:
print(" palindrome")
else:
print("not palindrome")

Shorthand

# One-Liner
def is_palindrome(phrase): return phrase == phrase[::-1]
print(is_palindrome("maam"))
print(is_palindrome("cat"))
print(is_palindrome("rats live on no evil star"))
'''
True
False
True
'''

Swapping Two Variables

We can use one of the different methods to swap two variables is to use a temporary variable, and the efficient way is given below.

Usual Solution

The right-hand side y, x is evaluated; that is to say, a tuple of two elements is created in the memory. The two elements are the objects designated by the identifiers y and x that was existing before the instruction is encountered during the execution of the program.

Just after the creation of this tuple, no assignment of this tuple object has still been made, but it doesn’t matter. Python internally knows where it is.

Then, the left-hand side is evaluated; that is to say, the tuple is assigned to the left-hand side.

As the left-hand side is composed of two identifiers, the tuple is unpacked in order that the first identifier is assigned to the first element of the tuple. And the second identifier y is assigned to the second element of the tuple.

Shorthand

# Python shorthand for swapping
x,y=10,5
print(x,y)
x,y=y,x
print(x,y)

Reading a File

Python provides built-in functions for creating, writing, and reading files.

Usual Solution

Shorthand

#one-liner
print([line.strip() for line in open("readFileDefault.py")])

Squares of number

Here is an example you will find useful. We are trying to find all the squares of numbers from 0. Just look at the shorthand. This is pretty impressive.

Usual Solution

# BEFORE
squares = []
for i in range(10):
squares.append(i**2)
print(squares)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Shorthand

# AFTER
print([i**2 for i in range(10)])

If Else

In Python, if-else serves as a conditional statement that helps one make decisions and execute code. But the general procedure is a bit boring, I mean time-dependent, so if we use Python one-liner, it will take less time, and the code will be efficient. Below are examples of both General Procedure and One-liner procedures. Check it out.

Usual solution

a = 5
b = 10
if b > a:
print("b is greater than a")
#output: b is greater than a

Shorthand

a,b = 5,10
print("A") if a > b else print("B")
#Output : B

Lambda function

Here is a block of code taken as an example which is done in General procedure, but if I want to make this code more efficient, then I can do it through Lambda Function, which is shown below.

Learn a little about the lambda function before looking at the example.

The lambda function is a small anonymous function that accepts the number of arguments but can only one expression.

lambda arguments: expression   # The expression is executed and the result is returned

This is the general syntax of the lambda function. Okay, now you can see the code below.

Usual solution

f = 5 + 5
print(f + f)

Shorthand

print((lambda f: f + f)(5 + 5))

Isn’t that interesting?

Yeah, that sounds pretty crap to me, Looks like BT ain’t for me either. So let’s start with the next example.

Factorial function

Factorial is a positive integer that is expressed as n! Which you must know, now you can see the code below.

Usual Solution

#general
Def fac(a):
if a == 0 or a == 1:
return 1
else:
return a*fac(a-1)
print(fac(5))

Shorthand

import math
print(math.factorial(5))

Patterns

Different programming languages ​​usually use loops for patterns. But now, we will see how to do this using Python’s Join function without using loops more easily.

Usual Solution

Shorthand

# one liner code for half pyramid pattern
n = 5
print('\n'.join('* ' * i for i in range(1, n + 1)))

Write a function

See, we have created a function here called fun and x * 5 as the return value, which will show me the return.

Usual solution

def fun(x):
return x*5
print(fun(3))

Shorthand

print((lambda fun: f(3))(lambda x: x*5))

Python one-liner is a topic that makes code more Pythonic. Studying Python one-liners forces you to think clearly and concisely. When you’re making every single code symbol count, there’s no room for sparse and unfocused coding.

Thank you for reading.

Have a great day!

Leave a Reply

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