Fundamentals 13 min read

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, classes, and more, each with concise explanations and ready‑to‑run examples to help developers write cleaner, more efficient code.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
20 Useful Python One‑Liner Code Snippets

This article shares a collection of 20 useful Python one‑liner snippets that demonstrate how to accomplish common tasks in a single line of code, making scripts shorter and more readable.

1. One‑line For Loop

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

<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 way
result = [x for x in mylist if x > 250]
print(result)  # [300, 400, 500]</code>

2. One‑line While Loop

Two approaches to write a while loop in a single line.

<code># Method 1 Single Statement
while True: print(1)  # infinite 1
# Method 2 multi‑statement
x = 0
while x < 5: print(x); x = x + 1  # 0 1 2 3 4</code>

3. One‑line If‑Else

Use the ternary operator to place an if‑else expression on one line.

<code># if‑else in one line
print("Yes") if 8 > 9 else print("No")  # No
E = 2
print("High") if E == 5 else print("DataSTUDIO") if E == 2 else print("Low")  # DataSTUDIO
if 3 > 2: print("Exactly")  # Exactly</code>

4. One‑line Dictionary Merge

Combine two dictionaries using either update() 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 with a conditional return or use a lambda expression.

<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

Calculate Fibonacci numbers with a recursive one‑liner.

<code># 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</code>

7. One‑line List Filtering

Filter even numbers from a list using a list comprehension.

<code># list filtering in one line
mylist = [2, 3, 5, 8, 9, 12, 13, 15]
result = [x for x in mylist if x % 2 == 0]
print(result)  # [2, 8, 12]</code>

8. One‑line Exception Handling

Wrap a try‑except block inside an exec() call.

<code># one‑line exception handling
try:
    print(x)
except:
    print("Error")
# one‑line way
exec('try:print(x) \nexcept:print("Error")')</code>

9. One‑line List to Dictionary

Convert a list to a dictionary using enumerate() in a single line.

<code># list to dict in one line
mylist = ["John", "Peter", "Mathew", "Tom"]
mydict = dict(enumerate(mylist))
print(mydict)  # {0: 'John', 1: 'Peter', 2: 'Mathew', 3: 'Tom'}</code>

10. One‑line Multiple Assignment

Assign several variables at once.

<code># multiple variables
a, b, c = 5, 7, 10
print(a, b, c)  # 5 7 10</code>

11. One‑line Value Swap

Swap two variables without a temporary variable.

<code># swap in one line
v1, v2 = 100, 200
v1, v2 = v2, v1
print(v1, v2)  # 200 100</code>

12. One‑line Sorting

Sort a list using the sort() method or the sorted() function.

<code># 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]</code>

13. One‑line File Reading

Read a file into a list with a single comprehension.

<code># read file in one line
data = [line.strip() for line in open("data.txt", "r")]
print(data)  # ['hello world', 'Hello Python']</code>

14. One‑line Class

Define a simple class or use namedtuple in a single line.

<code># class in one line
Emp = lambda: None; Emp.name = "云朵君"; Emp.age = 22
print(Emp.name, Emp.age)  # 云朵君 22
from collections import namedtuple
Emp = namedtuple('Emp', ['name', 'age'])('云朵君', 22)
print(Emp.name, Emp.age)  # 云朵君 22</code>

15. One‑line Semicolon

Separate multiple statements on a single line using semicolons.

<code># one‑line with semicolons
a = "Python"; b = "编程"; c = "语言"; print(a, b, c)  # Python 编程 语言</code>

16. One‑line Print

Print a range of numbers without an explicit loop.

<code># one‑line print
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.

<code># map in one line
print(list(map(lambda a: a + 2, [5, 6, 7, 8, 9, 10])))  # [7, 8, 9, 10, 11, 12]</code>

18. One‑line Delete Multiple List Elements

Remove every second element from a list using slice deletion.

<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 without a loop.

<code># print pattern in one line
print('😀' * 3)  # 😀😀😀
print('😀' * 2)  # 😀😀
print('😀' * 1)  # 😀</code>

20. One‑line Prime Finder

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

<code># find primes in one line
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]</code>

These snippets illustrate how Python’s expressive syntax can condense common programming patterns into concise one‑liners, helping developers write more compact and maintainable code.

PythonProgrammingcode 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.