20 Extremely Useful Python One-Liners You Must Know
Useful Python one-liner Snippets to solve any coding problem in just one line

In this blog, I will share 20 Python one-liners that you can easily learn in 30 seconds or less time on each. This one-liner code will save your time and will make your code look cleaner and easy to read.
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.
#For loop in One linemylist = [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, I had shown 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 53# — 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]”.
I had shown 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.
#if Else in One Line#Example 1 if elseprint("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 ifif 3 > 2: print("Exactly") # Exactly4# — Merge Dictionary in One Line
This One line Snippet will show you how to merge two dictionaries into one with One Line of code. Below I have shown two methods to merge dictionaries.
# Merge Dictionary in One Lined1 = { 'A': 1, 'B': 2 }
d2 = { 'C': 3, 'D': 4 }#method 1
d1.update(d2)
print(d1) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}#method 2
d3 = {**d1, **d2}
print(d3) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}5# — Function in One Line
We had 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.
#Function in One Line#method 1def fun(x): return True if x % 2 == 0 else False
print(fun(2)) # False#method 2fun = lambda x : x % 2 == 0
print(fun(2)) # True
print(fun(3)) # False6# — 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.
# Recursion in One Line#Fibonaci example with one line Recursiondef Fib(x): return 1 if x in {0, 1} else Fib(x-1) + Fib(x-2)
print(Fib(5)) # 8print(Fib(15)) # 9877# — Array Filtering in One Line
Python lists can be filtered in one line of code by using the list comprehension method. Let take the example of filtering a list with even numbers.
# Array Filtering in One Linemylist = [2, 3, 5, 8, 9, 12, 13, 15]#Normal Wayresult = []
for x in mylist:
if x % 2 == 0:
result.append(x)print(result) # [2, 8, 12]#One Line Wayresult = [x for x in mylist if x % 2 == 0]
print(result) # [2, 8, 12]8# — Exception Handling One Line
We used Exception handling to deal with runtimes errors in Python. Do you know we can write this Try Except statement in One-Line? By using the exec() statement we can do this.
# Exception Handling in One Line#Original Way
try:
print(x)
except:
print("Error")#One Line Way
exec('try:print(x) \nexcept:print("Error")') # Error9# — List to Dictionary in One Line
We can convert List to Dictionary in One Line using Python enumerate() function. Pass the list in enumerate() and use dict() to convert the final output in dictionary format.
# Dictionary in One linemydict = ["John", "Peter", "Mathew", "Tom"]mydict = dict(enumerate(mydict))print(mydict) # {0: 'John', 1: 'Peter', 2: 'Mathew', 3: 'Tom'}10# — Multi-Variable in One line
Python allows multiple variable assignments in one line. Below example code will show you how to do that.
#Multi Line Variable#Normal Way
x = 5
y = 7
z = 10
print(x , y, z) # 5 7 10#One Line way
a, b, c = 5, 7, 10
print(a, b, c) # 5 7 1011# — Swap in One Line
Swapping is an interesting task in Programming and always required a third variable name temp to save swap values. This One line snippet will show you how to swap values in one line without any temp variable.
#Swap in One Line#Normal wayv1 = 100
v2 = 200
temp = v1
v1 = v2
v2 = temp
print(v1, v2) # 200 100# One Line Swapping
v1, v2 = v2, v1
print(v1, v2) # 200 10012# — Sort in One Line
Sorting is a general problem in Programming and Python had many built-in methods to solve this sorting problem. Below is the code example that will show how to sort in one line.
# Sort in One Linemylist = [32, 22, 11, 4, 6, 8, 12]
# method 1mylist.sort()
print(mylist) # # [4, 6, 8, 11, 12, 22, 32]print(sorted(mylist)) # [4, 6, 8, 11, 12, 22, 32]13# — Read File in One Line
It is possible to read the file in one line correctly without using the statement or normal reading method.
#Read File in One Line#Normal Waywith open("data.txt", "r") as file:
data = file.readline()
print(data) # Hello world#One Line Waydata = [line.strip() for line in open("data.txt","r")]
print(data) # ['hello world', 'Hello Python']14# — 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.
# Class in One Line#Normal way
class Emp:
def __init__(self, name, age):
self.name = name
self.age = ageemp1 = Emp("Haider", 22)
print(emp1.name, emp1.age) # Haider 22#One Line Way#method 1 Lambda with Dynamic ArtibutesEmp = lambda: None; Emp.name = "Haider"; Emp.age = 22print(Emp.name, Emp.age) # Haider 22#method 2
from collections import namedtupleEmp = namedtuple('Emp', ["name", "age"]) ("Haider", 22)
print(Emp.name, Emp.age) # Haider 2215# — Semi-Colon in One Line
The semi-Colon in one line snippet will show you how to write multiple lines of code in one using semi-colons.
# Semi colon in One Line#example 1
a = "Python"; b = "Programming"; c = "Language"; print(a, b, c)#output:
# Python Programming Language16# — Print in One Line
This is not much important Snippet but it is useful sometimes when you don’t need to use a loop to do a task.
# Print in One Line#Normal Wayfor x in range(1, 5):
print(x) # 1 2 3 4#One Line Wayprint(*range(1, 5)) # 1 2 3 4
print(*range(1, 6)) # 1 2 3 4 517# — 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.
#Map in One Lineprint(list(map(lambda a: a + 2, [5, 6, 7, 8, 9, 10])))#output
# [7, 8, 9, 10, 11, 12]18# — Delete Mul Element in List One Line
You can now delete multiple elements in the List in one line of code using the del method with little modification.
# Delete Mul Element in One Linemylist = [100, 200, 300, 400, 500]del mylist[1::2]print(mylist) # [100, 300, 500]19# — Print Pattern in One Line
Now you no longer need to use Loop for printing the same pattern. You can use Print statement and asterisk (*) to do the same thing in one line of code.
# Print Pattern in One Line# Normal Way
for x in range(3):
print('😀')# output
# 😀 😀 😀#One Line wayprint('😀' * 3) # 😀 😀 😀
print('😀' * 2) # 😀 😀
print('😀' * 1) # 😀20# — 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.
# Find Prime Numberprint(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]Final Thoughts
I had shared the useful and interesting one-liner Python snippets with you. I hope you enjoy and learn something. Share it with your friends and other Python Programmers you know. Feel free to leave a response. Happy Codding!
Learn More
Are you a Python Fan and want some more Python shots, Check out my below Python articles? 😀.
More content at plainenglish.io





