Fundamentals 13 min read

20 Python One‑Liner Tricks for Concise and Readable Code

This article showcases twenty practical Python one‑liner examples that demonstrate how to write loops, conditionals, data‑structure operations, functions, recursion, file handling, and other common tasks in a single, compact line of code, complete with explanations and ready‑to‑run snippets.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
20 Python One‑Liner Tricks for Concise and Readable Code

This article presents twenty useful Python one‑liner examples, each accompanied by a brief description and the exact code, illustrating how to perform common programming tasks such as loops, conditionals, data‑structure manipulation, functions, recursion, file I/O, and more in a single line.

1 One‑line For Loop

Use a list comprehension to filter values greater than 250 in a single line.

mylist = [200, 300, 400, 500]
# normal way
result = []
for x in mylist:
    if x > 250:
        result.append(x)
print(result)  # [300, 400, 500]
# one‑line version
result = [x for x in mylist if x > 250]
print(result)  # [300, 400, 500]

2 One‑line While Loop

Show two ways to write a while loop in a single line, including an infinite loop and a bounded loop.

# method 1 – single statement
while True: print(1)  # infinite 1
# method 2 – multiple statements
x = 0
while x < 5: print(x); x = x + 1  # 0 1 2 3 4

3 One‑line IF‑Else Statement

Demonstrate the ternary operator for a one‑line conditional expression.

# if‑else in one line
print("Yes") if 8 > 9 else print("No")  # No
# if‑elif‑else using nested ternary
E = 2
print("High") if E == 5 else print("数据STUDIO") if E == 2 else print("Low")
# single if in one line
if 3 > 2: print("Exactly")  # Exactly

4 One‑line Dictionary Merge

Combine two dictionaries using either the update method or dictionary unpacking.

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 One‑line Function

Define a function in a single line using a regular definition with a ternary return or a lambda expression.

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

6 One‑line Recursion

Implement a recursive Fibonacci function in a single line.

# one‑line recursive Fibonacci
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

7 One‑line List Filtering

Filter even numbers from a list using a list comprehension.

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 One‑line Exception Handling

Execute a try‑except block in a single line using exec() .

# normal way
try:
    print(x)
except:
    print("Error")
# one‑line way
exec('try:print(x) \nexcept:print("Error")')  # Error

9 One‑line List to Dictionary

Convert a list to a dictionary using enumerate() and dict() in one line.

mydict = ["John", "Peter", "Mathew", "Tom"]
mydict = dict(enumerate(mydict))
print(mydict)  # {0: 'John', 1: 'Peter', 2: 'Mathew', 3: 'Tom'}

10 One‑line Multiple Variable Assignment

Assign several variables simultaneously in a single line.

# 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 10

11 One‑line Value Swap

Swap two variables without a temporary variable.

# normal way
v1 = 100
v2 = 200
temp = v1
v1 = v2
v2 = temp
print(v1, v2)  # 200 100
# one‑line swap
v1, v2 = v2, v1
print(v1, v2)  # 200 100

12 One‑line Sorting

Sort a list in place or obtain a sorted copy in a single line.

mylist = [32, 22, 11, 4, 6, 8, 12]
# method 1 – in‑place sort
mylist.sort()
print(mylist)  # [4, 6, 8, 11, 12, 22, 32]
# method 2 – using sorted()
print(sorted(mylist))  # [4, 6, 8, 11, 12, 22, 32]

13 One‑line File Reading

Read all lines from a file into a list without an explicit loop.

# 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 One‑line Class Definition

Define a simple class or equivalent structure in a single line using a lambda or namedtuple .

# normal class
class Emp:
    def __init__(self, name, age):
        self.name = name
        self.age = age
emp1 = Emp("云朵君", 22)
print(emp1.name, emp1.age)  # 云朵君 22
# one‑line using lambda
Emp = lambda: None; Emp.name = "云朵君"; Emp.age = 22
print(Emp.name, Emp.age)  # 云朵君 22
# one‑line using namedtuple
from collections import namedtuple
Emp = namedtuple('Emp', ['name', 'age'])("云朵君", 22)
print(Emp.name, Emp.age)  # 云朵君 22

15 One‑line Semicolon Usage

Execute multiple statements on a single line using semicolons.

a = "Python"; b = "编程"; c = "语言"; print(a, b, c)  # Python 编程 语言

16 One‑line Print

Print a range of numbers without an explicit loop.

# 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 5

17 One‑line map Function

Apply a lambda to each element of a list using map() in a single line.

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

18 Delete Multiple Elements in One Line

Remove every second element from a list using slice deletion.

mylist = [100, 200, 300, 400, 500]
del mylist[1::2]
print(mylist)  # [100, 300, 500]

19 One‑line Pattern Printing

Print repeated emoji patterns without a loop.

# normal way
for x in range(3):
    print('😀')
# one‑line
print('😀' * 3)  # 😀😀😀
print('😀' * 2)  # 😀😀
print('😀' * 1)  # 😀

20 One‑line Prime Number Finder

Generate a list of prime numbers within a range using filter() and a lambda.

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

These concise snippets help reduce boilerplate, improve readability, and demonstrate Python's expressive power for everyday programming tasks.

programmingcode snippetsOne‑Linertips
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.