20 Powerful Python One‑Liners to Write Cleaner Code in Seconds
This article presents twenty practical Python one‑line snippets—including loops, conditionals, dictionary merging, file reading, recursion, and more—demonstrating how to condense common tasks into concise, readable code that saves time and improves clarity.
In this article I share 20 Python one‑line code snippets that you can learn in 30 seconds or less. These one‑liners save time and make your code look cleaner and easier to read.
1. For loop
Use list comprehension to write a for loop in one line. Example filters values greater than 250.
# For loop in One line
mylist = [100, 200, 300, 400, 500]
# Original 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
Show two ways to write a while loop in one line.
# method 1 Single Statement
whileTrue: print(1) # infinite 1
# method 2 Multiple Statement
x = 0
while x < 5: print(x); x = x + 1 # 0 1 2 3 43. IF‑Else statement
Use the ternary operator to write an if‑else statement in one line. Multiple ternary operators can emulate elif.
# if else in One Line
# Example 1
print("Yes") if 8 > 9 else print("No") # No
# Example 2
E = 2
print("High") if E == 5 else print("Medium") if E == 2 else print("Low") # Medium
# Example 3
if 3 > 2: print("Exactly") # Exactly4. Merge dictionaries
Two methods to merge two dictionaries in one line.
# Merge Dictionary in One Line
d1 = {'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. Write functions
Two ways to define a function in one line: a regular definition with a ternary return, and a lambda expression.
# Function in One Line
# 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)) # False6. One‑line recursion
Find Fibonacci numbers using a one‑line recursive function.
# Recursion in One Line
# Fibonacci example
def Fib(x): return 1 if x in {0, 1} else Fib(x-1) + Fib(x-2)
print(Fib(5)) # 8
print(Fib(15)) # 9877. List filtering
Filter a list of numbers to keep only even values using list comprehension.
# Array Filtering in One Line
mylist = [2, 3, 5, 8, 9, 12, 13, 15]
# Normal way
result = []
for x in mylist:
if x % 2 == 0:
result.append(x)
print(result) # [2, 8, 12]
# One Line way
result = [x for x in mylist if x % 2 == 0]
print(result) # [2, 8, 12]8. Exception handling
Write a try‑except block in one line using exec.
# Exception Handling in One Line
# Original way
try:
print(x)
except:
print("Error")
# One Line way
exec('try:print(x)
except:print("Error")') # Error9. List to dictionary
Convert a list to a dictionary in one line with enumerate and dict.
# Dictionary in One line
mydict = ["John", "Peter", "Mathew", "Tom"]
mydict = dict(enumerate(mydict))
print(mydict) # {0: 'John', 1: 'Peter', 2: 'Mathew', 3: 'Tom'}10. Multiple variable assignment
Assign several variables in a single line.
# 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. Swapping values
Swap two variables without a temporary variable.
# Swap in One Line
# Normal way
v1 = 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. Sorting
Sort a list in one line using list.sort() or sorted().
# Sort in One Line
mylist = [32, 22, 11, 4, 6, 8, 12]
mylist.sort()
print(mylist) # [4, 6, 8, 11, 12, 22, 32]
print(sorted(mylist)) # [4, 6, 8, 11, 12, 22, 32]13. Read file
Read a file in one line without explicit loops.
# Read File in One Line
# 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("data.txt", "r")]
print(data) # ['hello world', 'Hello Python']14. Class definition
Two one‑line approaches to create a simple class: using a lambda with dynamic attributes and using namedtuple.
# Class in One Line
# Normal way
class Emp:
def __init__(self, name, age):
self.name = name
self.age = age
emp1 = Emp("Haider", 22)
print(emp1.name, emp1.age) # Haider 22
# One Line method 1 (lambda)
Emp = lambda: None; Emp.name = "Haider"; Emp.age = 22
print(Emp.name, Emp.age) # Haider 22
# One Line method 2 (namedtuple)
from collections import import namedtuple
Emp = namedtuple('Emp', ['name', 'age'])("Haider", 22)
print(Emp.name, Emp.age) # Haider 2215. Semicolon usage
Write multiple statements on a single line using semicolons.
# Semi colon in One Line
# example 1
a = "Python"; b = "Programming"; c = "Language"; print(a, b, c)
# output: Python Programming Language16. One‑line printing
Print a range of numbers without a loop by unpacking the range.
# Print in One Line
# Normal way
for x in range(1, 5):
print(x) # 1 2 3 4
# One Line way
print(*range(1, 5)) # 1 2 3 4
print(*range(1, 6)) # 1 2 3 4 517. Map function
Apply a function to each element of a list in one line using map.
# Map in One Line
print(list(map(lambda a: a + 2, [5, 6, 7, 8, 9, 10]))) # [7, 8, 9, 10, 11, 12]18. Delete multiple list elements
Remove several elements from a list in one line with del and slicing.
# Delete Mul Element in One Line
mylist = [100, 200, 300, 400, 500]
del mylist[1::2]
print(mylist) # [100, 300, 500]19. Print pattern
Print repeated characters without a loop using multiplication.
# Print Pattern in One Line
print('😀' * 3) # 😀😀😀
print('😀' * 2) # 😀😀
print('😀' * 1) # 😀20. Find prime numbers
Generate a list of prime numbers within a range in a single line.
# Find Prime Number
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]These one‑line Python snippets provide quick, elegant solutions for common programming tasks, helping you write more concise and maintainable code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
