Skip to main content

Command Palette

Search for a command to run...

Improving Python Code by writing one liners

Updated
โ€ข5 min read
Improving Python Code by writing one liners
N

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

More from this blog

Naveen P.N's Tech Blog

94 posts