Improving Python Code by writing one liners

I am a Tech Enthusiast having 13+ years of experience in ๐๐ as a ๐๐จ๐ง๐ฌ๐ฎ๐ฅ๐ญ๐๐ง๐ญ, ๐๐จ๐ซ๐ฉ๐จ๐ซ๐๐ญ๐ ๐๐ซ๐๐ข๐ง๐๐ซ, ๐๐๐ง๐ญ๐จ๐ซ, with 12+ years in training and mentoring in ๐๐จ๐๐ญ๐ฐ๐๐ซ๐ ๐๐ง๐ ๐ข๐ง๐๐๐ซ๐ข๐ง๐ , ๐๐๐ญ๐ ๐๐ง๐ ๐ข๐ง๐๐๐ซ๐ข๐ง๐ , ๐๐๐ฌ๐ญ ๐๐ฎ๐ญ๐จ๐ฆ๐๐ญ๐ข๐จ๐ง ๐๐ง๐ ๐๐๐ญ๐ ๐๐๐ข๐๐ง๐๐. I have ๐๐๐๐๐๐๐ ๐๐๐๐ ๐๐๐๐ 10,000+ ๐ฐ๐ป ๐ท๐๐๐๐๐๐๐๐๐๐๐๐ and ๐๐๐๐ ๐๐๐๐๐ ๐๐๐๐ ๐๐๐๐ 500+ ๐๐๐๐๐๐๐๐ ๐๐๐๐๐๐๐๐ in the areas of ๐๐จ๐๐ญ๐ฐ๐๐ซ๐ ๐๐๐ฏ๐๐ฅ๐จ๐ฉ๐ฆ๐๐ง๐ญ, ๐๐๐ญ๐ ๐๐ง๐ ๐ข๐ง๐๐๐ซ๐ข๐ง๐ , ๐๐ฅ๐จ๐ฎ๐, ๐๐๐ญ๐ ๐๐ง๐๐ฅ๐ฒ๐ฌ๐ข๐ฌ, ๐๐๐ญ๐ ๐๐ข๐ฌ๐ฎ๐๐ฅ๐ข๐ณ๐๐ญ๐ข๐จ๐ง๐ฌ, ๐๐ซ๐ญ๐ข๐๐ข๐๐ข๐๐ฅ ๐๐ง๐ญ๐๐ฅ๐ฅ๐ข๐ ๐๐ง๐๐ ๐๐ง๐ ๐๐๐๐ก๐ข๐ง๐ ๐๐๐๐ซ๐ง๐ข๐ง๐ . I am interested in ๐ฐ๐ซ๐ข๐ญ๐ข๐ง๐ ๐๐ฅ๐จ๐ ๐ฌ, ๐ฌ๐ก๐๐ซ๐ข๐ง๐ ๐ญ๐๐๐ก๐ง๐ข๐๐๐ฅ ๐ค๐ง๐จ๐ฐ๐ฅ๐๐๐ ๐, ๐ฌ๐จ๐ฅ๐ฏ๐ข๐ง๐ ๐ญ๐๐๐ก๐ง๐ข๐๐๐ฅ ๐ข๐ฌ๐ฌ๐ฎ๐๐ฌ, ๐ซ๐๐๐๐ข๐ง๐ ๐๐ง๐ ๐ฅ๐๐๐ซ๐ง๐ข๐ง๐ new subjects.
The official python wiki website states the following about one-liners:
โYou may ask: why should I care? The answer is profound: if you cannot read and write one-liner code snippets, how can you ever hope to read and write more complicated codebases? Python one-liners can be just as powerful as a long and tedious program written in another language designed to do the same thing. In other languages (think: Java) this would be nearly impossible, but in Python, itโs a lot easier to do. The trick is to think of something that will โdo a lot with a little.โ
Swapping two variables
Swapping two variables requires creating a temporary variable in languages such as C++ and Java. This makes it a cumbersome process in which many people are prone to make mistakes, especially in complex and long codes. Python allows us to swap two variables without the need for a third variable.
a = 10
b = 12
# Swapping a and b - multi-line implementation
x = a #using x as temporary variable
a = b
b = x
# Python one-liner
a,b = b,a
print(a),print(b)
### Output: 12,10
Reverse a list
Python has a very interesting way of reversing lists using subscripting, in addition to the inbuilt functions.
#reversing python list
lst = [2,3,22,4,1]
lst[::-1]
### Output: [1,4,22,3,2]
Ternary Operator
Ternary operators are the expressions that evaluate conditional statements and return value based on whether the statement is True or False.
Although there is not an actual ternary operator with a proper symbol, python makes a simple โIf Elseโ work as the ternary operator for simple conditions.
#multi line implementation
if 4%2==0:
print("even")
else:
print("odd")
#Ternary operator in python
print("even") if 4%2==0 else print("odd")
#### Output: even
List Comprehension
Iterating over a list/dictionary using loops having multiple line statements is a daunting task, luckily, python provides a one-line alternative to this โ one-liner comprehensions.
List comprehension is a powerful method to populate a list.
## multi-line implementation
##creating a list of numbers
result = []
for i in range(0,10):
result.append(i)
# list comprehension:one-liner
result = [i for i in range(0,10)]
print(result)
### Output: [0,1,2,3,4,5,6,7,8,9,10]
List comprehension can be conditional too.
#list comprehension with ternary operator
#finding square of even numbers
result2 = [i**2 for i in range(10) if i%2==0]
print(result2)
### Output: [0, 4, 16, 36, 64]
In the above case, we use the ternary if-else combined with a for loop for list comprehension.
Dictionary Comprehension
Similar to a list comprehension, dictionary comprehension is also possible in python.
# Dictionary comprehension
myDict = {x: x**2 for x in [1,2,3,4,5]}
print(myDict)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
myDict contains the numbers 1 to 5 as keys and their squares as the corresponding values.
Lambda functions
A lambda function is a small, anonymous function. An anonymous function means that it has no name and no conventional definition. A lambda function is written in a single line and can take any number of arguments but can have only a single expression.
## lambda function to square a number
sqr = lambda x: x * x
sqr(10)
## Output: 100
The lambda function can be extended to carry out more complicated tasks such as finding prime numbers in a range of numbers, obtaining the Fibonacci series, or even implementing quicksort.
## lambda function to find prime number
list(filter(lambda x:all(x % y != 0 for y in range(2, x)), range(2, 13)))
## Output: [2, 3, 5, 7, 11]
The above code gives us all the prime numbers between 2 and 12.
The filter function takes 2 arguments: 1)Function to filter the values(lambda function) 2)Input values to the filter function. The input values range from 2 to 12, which goes as input to the lambda function, and within the lambda function, we are checking whether the input value is divisible by numbers from 2 to (input_value-1).
Read file input into a list
Files can be read in just a single line of code in python using the following expression.
## Reading file contents into a list: multi-line
file_lines = []
with open(filename) as file:
for line in file:
file_lines.append(line.strip())
file_lines = [line.strip() for line in file]
## Reading file contents into a list: one-liner
file_lines = [line.strip() for line in open(filename)]
file_lines list contains all the lines in the input text file. The strip() function removes the leading and trailing spaces from the text.
Binary to Decimal
Python has an interesting method of converting a binary number to decimal without the use of an inbuilt function. It might be the simplest way to convert a binary number to decimal in any programming language so far.
## converting a binary number to int
n = '100' ##binary 100
dec_num = int(n,base = 2)
print(dec_num)
## Output: 4
Where n can be any binary number.
Combinations and Permutations
It normally takes a lot of effort to find all combinations of a set in a single line. Using itertools.combinations() makes it much easier to complete the task.
from itertools import combinations
print(list(combinations([1, 2, 3, 4], 2)))
## Output: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
Finding all the permutations of a set can also be done similarly using a one-liner, which can otherwise be a very long piece of code.
from itertools import permutations
print(list(permutations([1, 2, 3, 4], 2)))
##Output: [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
Longest String from a List
To find the longest string in a list conventionally, we would have to iterate through it once while checking the length of every string in a list. However, python gives us an easier way to do so in the following manner.
words = ['This', 'is', 'a', 'list', 'of', 'keyword']
print(max(words, key=len))
##Output: keyword
Conclusion
One-liners are both interesting and essential to write good code. One should always try to code in the minimum number of lines while maintaining the functionality and meaning of the code and try to make it a habit.
Thank you!
You can get all my posts in your inbox Subscribe here



