20 Useful Python One-Liner Code Snippets
This article presents 20 practical Python one‑liner code snippets covering loops, conditionals, data structures, functions, recursion, file handling, and more, demonstrating how to write concise, readable code that solves common tasks in a single line.
In this article, the author shares 20 Python one‑liner 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. One-line For loop
Using a list comprehension, you can write a for loop in a single line to filter values less than 250.
<code># For loop in one 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]</code>2. One-line While loop
This snippet shows two ways to write a while loop in a single line.
<code># 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 5</code>3. One-line IF‑Else statement
Use the ternary operator to write an if‑else statement on one line. Multiple ternary operators can emulate elif.
<code># if‑else in one line
print("Yes") if 8 > 9 else print("No") # No
# if‑elif‑else example
E = 2
print("High") if E == 5 else print("Data STUDIO") if E == 2 else print("Low") # Data STUDIO
# only if example
if 3 > 2: print("Exactly") # Exactly</code>4. One-line dictionary merge
Combine two dictionaries into one using either the update method or dictionary unpacking.
<code># Merge dictionaries 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}</code>5. One-line function
Define a function in one line using a ternary expression or a lambda.
<code># 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)) # False</code>6. One-line recursion
Implement a recursive Fibonacci function in a single line.
<code># One‑line recursion
# 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)) # 987</code>7. One-line list filtering
Filter a list using a list comprehension in one line.
<code># List 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]</code>8. One-line exception handling
Use exec() to write a try‑except block on a single line.
<code># One‑line exception handling
# Normal way
try:
print(x)
except:
print("Error")
# One‑line way
exec('try:print(x) \nexcept:print("Error")') # Error</code>9. One-line list to dictionary
Convert a list to a dictionary using enumerate() and dict() in one line.
<code># List to dict in one line
mydict = ["John", "Peter", "Mathew", "Tom"]
mydict = dict(enumerate(mydict))
print(mydict) # {0: 'John', 1: 'Peter', 2: 'Mathew', 3: 'Tom'}</code>10. One-line multiple variable assignment
Assign several variables in a single line.
<code># Multiple variables
# 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</code>11. One-line value swap
Swap two values without a temporary variable.
<code># Swap in one line
v1, v2 = v2, v1
print(v1, v2) # 200 100</code>12. One-line sorting
Sort a list using the built‑in sort() method or the sorted() function in one line.
<code># Sorting 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]</code>13. One-line file reading
Read a file in a single line using a list comprehension.
<code># One‑line file read
# 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']</code>14. One-line class definition
Define a simple class or namedtuple in a single line.
<code># One‑line class
# Method 1 using lambda
Emp = lambda:None; Emp.name = "云朵君"; Emp.age = 22
print(Emp.name, Emp.age) # 云朵君 22
# Method 2 using namedtuple
from collections import namedtuple
Emp = namedtuple('Emp', ['name', 'age'])('云朵君', 22)
print(Emp.name, Emp.age) # 云朵君 22</code>15. One-line semicolon usage
Separate multiple statements on one line with semicolons.
<code># One‑line with semicolons
a = "Python"; b = "编程"; c = "语言"; print(a, b, c) # Python 编程 语言</code>16. One-line printing
Print a range of numbers without an explicit loop.
<code># One‑line printing
print(*range(1, 5)) # 1 2 3 4
print(*range(1, 6)) # 1 2 3 4 5</code>17. One-line map function
Apply a lambda to each element of a list using map() in one line.
<code># One‑line map
print(list(map(lambda a: a + 2, [5, 6, 7, 8, 9, 10]))) # [7, 8, 9, 10, 11, 12]</code>18. One-line deletion of multiple list elements
Delete several elements from a list using slice notation in a single line.
<code># Delete multiple elements in one line
mylist = [100, 200, 300, 400, 500]
del mylist[1::2]
print(mylist) # [100, 300, 500]</code>19. One-line pattern printing
Print repeated characters using multiplication instead of a loop.
<code># One‑line pattern printing
print('' * 3) # (empty line of length 3)
print('' * 2)
print('' * 1)</code>20. One-line prime number search
Find prime numbers within a range using filter() and a lambda expression.
<code># One‑line prime search
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]</code>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.