10 Awesome Python One-Liners Look Like A Pro 😎

Β·

5 min read

10 Awesome Python One-Liners Look Like A Pro 😎

Hello, buddies! Python programs generally are smaller than other programming languages like Java. Programmers have to type relatively less and indentation requirements of the language make them readable all the time. However, Python programs can be made more concise using some one-liner codes. These can save time by having fewer codes to type πŸ˜‰

gif 1.gif

So today we're going to see some awesome Python one-liners. Scroll down!

1. For loop in One line

For loop is a multi-line statement, But in Python, we can write for loop in one line using the List Comprehension method. Let take an example of filtering values that are lesser than 250. Check out the Below code example.


mylist = [100, 200, 300, 400, 500]
#Orignal way
result = []
for x in mylist:
    if x > 250:
        result.append(x)
print(result) # [300, 400, 500]

#One Line Way
result = [x for x in mylist if x > 250]
print(result) # [300, 400, 500]

2. While Loop in One Line

This One-Liner snippet will show you how to use the While loop code in One Line, there are two methods of doing this.

#method 1 Single Statement
while True: print(1)  # infinite 1

#method 2 Multiple Statement
x = 0
while x < 5: print(x); x= x + 1  # 0 1 2 3 4 5

3. If Else Statement in One Line

Well, to write the IF Else statement in One Line we will use the ternary operator. Syntax of Ternary is [on true] if [expression] else [on false]

There are 3 examples in the below example code to make your understanding clear that how to use the ternary operator for one line if-else statement. To use the Elif statement we had to use multiple Ternary operators. πŸ‘‡


#Example 1 if else
print("Yes") if 8 > 9 else print("No")  # No

#Example 2 if elif else
E = 2
print("High") if E == 5 else print("Meidum") if E == 2 else print("Low") # Medium

#Example 3 only if
if 3 > 2: print("Exactly") # Exactly

4. Function in One Line

We have two methods to write Functions in one line, In the first method, we will use the same function definition with the ternary operator or one-line loop methods. The second method is to define functions with lambda. Check out the example code below for more clear understanding πŸ‘‡

#method 1
def fun(x): return True if x % 2 == 0 else False
print(fun(2)) # False
#method 2
fun = lambda x : x % 2 == 0 
print(fun(2)) # True
print(fun(3)) # False

5. Recursion in One Line

This One-Liner Snippet will show how to use Recursion in one line. we will use one line function definition with one line if-else statement. Below is an example of finding the Fibonacci numbers.

#Fibonaci example with one line Recursion
def Fib(x): return 1 if x in {0, 1} else Fib(x-1) + Fib(x-2)
print(Fib(5)) # 8
print(Fib(15)) # 987

6. Read File in One Line

It is possible to read the file in one line correctly without using the statement or normal reading method.

#Normal Way
with open("data.txt", "r") as file:
    data = file.readline()
    print(data) # Hello world
#One Line Way
data = [line.strip() for line in open("chat.txt","r")]
print(data) # ['hello buddies', 'Are you doing well?']

7. Class in One Line

Class is always multi-line work. But in Python, there are some ways in which you can use class-like features in One line of codes.

#Normal way 
class Emp:
    def __init__(self, name, age):
        self.name = name
        self.age = age
emp1 = Emp("Unity Buddy", 1000)
print(emp1.name, emp1.age) #  Unity Buddy 1000
#One Line Way
#method 1 Lambda with Dynamic Artibutes
Emp = lambda: None; Emp.name = "Unity Buddy"; Emp.age = 1000
print(Emp.name, Emp.age) # Unity Buddy 1000
#method 2

from collections import namedtuple
Emp = namedtuple('Emp', ["name", "age"]) ("Unity Buddy", 1000)
print(Emp.name, Emp.age) # Unity Buddy 1000

8. Map Function in One Line

The Map function is a higher-order function that applies. That applies a function to every element. Below is the Example that how we can use the map function in one line of Code.

print(list(map(lambda a: a + 2, [5, 6, 7, 8, 9, 10])))
#output
# [7, 8, 9, 10, 11, 12]

9. Find Prime Number in One Line

This snippet will show you how to write a one-liner code to find the Prime number within the range.

print(list(filter(lambda a: all(a % b != 0 for b in range(2, a)), range(2,20))))
#Output
# [2, 3, 5, 7, 11, 13, 17, 19]

10. Printing any data in an easy-to-read format

Do you sometimes have a lot of data or data which varies in type, and you want to print it all out to the terminal for further inspection but it all prints in one huge line and you can’t see anything? Well for that you can use the built-in pprint module in Python, this will automatically format your data and print it nicely to your terminal. Here I have a dictionary with random values and use the pprint function from the pprint module to print it out!

from pprint import pprint

data = {"ahead": {"between": "boy", "blew": "allow", "path": 1972198692, "inside": False, "fly": "throat", "toward": -1359495784.298975}}

pprint(data)

BONUS: Import all the libraries in one go

pyforest is a python module that can help us import all the libraries in a single line of python. You can expect all kinds of general use python libraries to get imported. This also includes most of the libraries used for machine learning tasks. This library also has some helper modules such as os, tqdm, re, and many more.

pip install pyforest

To check the list of libraries, run this dir(pyforest). After importing pyforest, you can directly run pd.read_csv() , sns.barplot() , os.chdir() and many more!

So buddies, that's it! Thanks for reading and happy Coding!

Β