Python One-Liners To Enhance Code Quality

I am a self-taught Python developer who loves to write on Python Programming and quite obsessed with Machine Learning.
Search for a command to run...

I am a self-taught Python developer who loves to write on Python Programming and quite obsessed with Machine Learning.
No comments yet. Be the first to comment.
When you’re building an application, one thing you can’t skip is API testing. Whether it’s a login flow, payment gateway, or a complex e-commerce workflow, ensuring your APIs behave correctly saves you from nasty surprises in production. I had alread...

PyPy is an implementation of Python written in RPython (Reduced Python) language, and it is seen as a replacement for CPython. PyPy claims that it is almost a drop-in replacement for CPython and can beat it on speed and memory usage. It supports libr...

You must have used functions provided by the os module in Python several times in your projects. These could be used to create a file, walk down a directory, get info on the current directory, perform path operations, and more. In this article, we’ll...

FastAPI is a fast and modern web framework known for its support for asynchronous REST API and ease of use. In this article, we’ll see how to stream videos on frontend in FastAPI. StreamingResponse Stream Local Video FastAPI provides a StreamingRespo...

Have you ever come across circular imports in Python? Well, it’s a very common code smell that indicates something’s wrong with the design or structure. Circular Import Example How does circular import occur? This import error usually occurs when two...
Python is known for its simplicity and readability. Python provides flexibility to write complex code straightforwardly, and writing code in Python is like writing the English language.
Python is popular because of its self-explanatory syntax and power to restrict long programs to a few lines. One-liners are one of the power Python has, allowing users to write a single-line code that runs multiple tasks simultaneously.
This article will show some one-line Python programs that help us in everyday programming, enhance productivity, and speed up our coding process.
We can use list comprehension for writing a multiline set of Python statements in a single line. We can write the for loop with an if-else condition in a single line instead of writing in multiple lines.
seq = ["Volkswagen", "Audi", "Porsche", "Jaguar"]
for cars in seq:
if "a" in cars:
print(cars)
else:
print(f"No match found in {cars}")
We can wrap the above code in a single line using list comprehension.
output = [cars if "a" in cars else f"No match found in {cars}" for cars in seq]
The Lambda function is also known as the anonymous function. We can define an anonymous function using a lambda keyword and then provide an expression.
num_cube = lambda num: num * num * num
print(num_cube(3))
An array is a collection of elements of the same data types stored in contiguous memory locations with assigned index values that help locate them.
import numpy as np
np.random.randint(16, size=(2, 3, 2))
The above code generates a 3D array of shapes (2, 3, 2) from random numbers between 0 and 16.
This operator is used to assign values to the variables within an expression. It is an assignment operator represented by the sign :=. This feature was added in Python version 3.8.
We have a Python program that takes the input from the user, if that input is 7, it will print something, if not, it will return nothing.
inp = input("Enter the number: ")
while inp == "7":
print("You found it")
break
The above code can be written in a single line.
while (number := input("Enter the number: ")) == "7": print(f"The hidden number {number} found.")
The most common way of generating random numbers is by using a library called random.
import random
random.sample(range(1, 99), 10)
This code will generate a list of 10 random numbers between 1 and 99.
We can use the RegEx (Regular Expression) to substitute any pattern. Let's say we have text data in which we have to substitute letters starting and ending from * (asterisk).
text = "The *big* data got bigger and bigger. It is called *big* data because of having *big* data"
The code to substitute the above pattern.
import re
re.sub('\*(.*?)\*', "small", text)
The pattern \*(.*?)\* matches the characters starting and ending with *, and it has a group capture that captures the text between *.
To remove the duplicate values from the Python list, convert that list to the set. Consider the following example to understand it better.
lst = [2, 3, 2, 3, 44, 3, 2, 45, 44]
new_lst = set(lst)
....
{2, 3, 44, 45}
All the duplicate values were removed because the set doesn't allow identical values.
When working on textual data in Python, the replace() method can come in handy to replace a particular text with a text of your choice.
text = “The big data got bigger and bigger. It is called big data because of having big data”
new_text = text.replace("data", "dataset")
print(new_text)
The above code will replace the word data with dataset.
If you are working on a project that wants to take multiple user inputs simultaneously, the following one-liner will come in handy.
input("Enter your inputs: ").split()
The user can enter unlimited inputs and get those in the form of a list because the split() method will convert the string input into a list.
Using a comma, we can assign multiple values to the variables simultaneously. A value of any data type can be assigned to the variable.
a, b, c = {1, 2, 3}, 5.5, "Hello World"
print(a, b, c)
....
{1, 2, 3} 5.5 Hello World
We assigned a set to variable a, a float to variable b, and a string to variable c.
We can write some data into a file by opening it with the open() function and then using the write() method.
with open("hello.txt", "w") as f: f.write("Welcome to GeekPython")
with open("hello.txt") as f: data = [line for line in f]
print(data)
In the above code, first, we open a file and use the for loop to read the content of the file line by line.
We can add a counter to each item in the existing list using Python's built-in enumerate() function.
seq = ["Volkswagen", "Audi", "Porsche", "Jaguar"]
var = list(enumerate(seq, start=0))
....
[(0, 'Volkswagen'), (1, 'Audi'), (2, 'Porsche'), (3, 'Jaguar')]
We can start counting from any number by providing the starting number to the start argument.
We can merge two iterators using the zip() function. It takes the iterable and iterates them parallelly, producing tuples of each item from the iterable.
languages = ["Python", "JavaScript", "C", "C++"]
founded = [1991, 1995, 1972, 1985]
mapping = list(zip(languages, founded))
We can sort a list in ascending or descending order. Let's say we have a list of names.
my_lst = ["Rishu", "Rishi", "Yashwant", "Abhishek", "Sachin", "Yogesh"]
To sort the above list in ascending order(alphabetically), we have to write the following code.
my_lst.sort()
...
['Abhishek', 'Rishi', 'Rishu', 'Sachin', 'Yashwant', 'Yogesh']
We can use the reverse=True inside the sort method to sort the list in descending order.
Copying files or even an entire directory can be overwhelming. We can automate the task of copying files or directories using the shutil module in Python.
import shutil
shutil.copytree('src_path', 'dst_path')
If we wanted to copy only the files.
shutil.copy('src_path', 'dst_path')
Python os module provides a method to list the directories of the specified path.
import os
dir = os.listdir("D:/SACHIN/Pycharm/one-liners")
If we use a traditional approach, we will write a Python program like the following.
# Using naive swapping
var = a
a = b
b = var
----------OR----------
# Using XOR swapping
x = x^y
y = x^y
x = x^y
Instead of using the two methods mentioned above, we can do it in a single line using commas.
a, b = b, a
We can use the reverse() method to reverse the order of the elements in the list.
seq = ["Volkswagen", "Audi", "Porsche", "Jaguar"]
seq.reverse()
The one-liners we've seen above help us in everyday programming and enhance our code quality. These single-line codes can save us lots of time.