100 Python One-Liners Everyone Should Know
Master the art of concise, elegant Python with these brilliant one-liners — from basic tricks to powerful expressions every developer…

Think Python is powerful? Wait until you see what it can do in just one line.
Master the art of concise, elegant Python with these brilliant one-liners — from basic tricks to powerful expressions every developer should know.
Whether you’re a seasoned Pythonista or a curious coder aiming to sharpen your skills, there’s something deeply satisfying about writing clean, expressive code in a single line.
Python’s elegant syntax and functional capabilities make it perfect for writing powerful one-liners. These aren’t just gimmicks — they’re practical, time-saving tricks that demonstrate the language’s flexibility.
In this article, we’ll explore 100 Python one-liners across categories like strings, lists, dictionaries, file handling, and even basic algorithms — all written to help you code smarter, not harder.
Writing one-liners isn’t just about showing off (although it does feel good). It’s about learning:
How to think functionally
How to chain built-ins and write clean expressions
How to simplify everyday problems
And yes — how to make your code look cool in reviews
Let’s dive into 50 Python one-liners that belong in your mental toolbox.
String Tricks
# 1. Reverse a string
"hello"[::-1]
# 2. Check for palindrome
lambda s: s == s[::-1]
# 3. Count vowels
sum(1 for c in "hello world" if c in "aeiou")
# 4. Remove duplicates
"".join(dict.fromkeys("aabbcc"))
# 5. Most frequent character
from collections import Counter; Counter("banana").most_common(1)[0][0]
# 6. Convert to title case
"this is title".title()
# 7. Check if all characters are digits
"12345".isdigit()
# 8. Replace vowels with '*'
"hello world".translate(str.maketrans("aeiou", "*****"))
# 9. Count words
len("How many words?".split())
# 10. Remove punctuation
import string; ''.join(c for c in "hello, world!" if c not in string.punctuation)
Number and Math Magic
# 11. Prime check
lambda x: x > 1 and all(x % i for i in range(2, int(x**0.5)+1))
# 12. Fibonacci (first 10)
fib = [0, 1]; [fib.append(fib[-1]+fib[-2]) for _ in range(8)]
# 13. Sum of digits
sum(map(int, str(1234)))
# 14. Factorial
from math import factorial; factorial(5)
# 15. GCD
from math import gcd; gcd(24, 36)
# 16. LCM
lambda a, b: abs(a*b) // gcd(a, b)
# 17. Round to 2 decimals
round(3.14159, 2)
# 18. Binary of a number
bin(42)[2:]
# 19. Convert binary to int
int("101010", 2)
# 20. Square root
import math; math.sqrt(16)
List Manipulations
# 21. Flatten nested lists
[i for sub in [[1,2],[3,4]] for i in sub]
# 22. Unique elements
list(set([1,2,2,3]))
# 23. Sort by second value
sorted([(1,3),(2,2),(3,1)], key=lambda x: x[1])
# 24. Intersection
list(set([1,2,3]) & set([2,3,4]))
# 25. Evens
[x for x in range(10) if x % 2 == 0]
# 26. Remove falsy values
list(filter(bool, [0, 1, '', 'hello', None]))
# 27. List of dictionaries
[{'id': i} for i in range(3)]
# 28. List of even squares
[x**2 for x in range(10) if x%2==0]
# 29. Find duplicates
[x for x in [1,2,2,3] if [1,2,2,3].count(x) > 1]
# 30. Chunk list
[ [1,2,3,4][i:i+2] for i in range(0, 4, 2) ]
Loops & Comprehensions
# 31. Squares
[x**2 for x in range(10)]
# 32. Filter positives
list(filter(lambda x: x > 0, [-2, 3, 0, 1]))
# 33. Flatten dict values
[v for values in {'a': [1,2], 'b': [3]}.values() for v in values]
# 34. Zip lists
list(zip([1,2], ['a','b']))
# 35. Cartesian product
[(x, y) for x in [1,2] for y in [3,4]]
# 36. Nested list comprehension
[[i*j for j in range(1, 4)] for i in range(1, 4)]
# 37. Reverse list
[1,2,3][::-1]
# 38. Enumerate list
list(enumerate(['a', 'b', 'c']))
# 39. Combine multiple lists
[x+y for x, y in zip([1,2], [3,4])]
# 40. Filter with list comprehension
[x for x in range(10) if x % 3 == 0]
Dictionary Hacks
# 41. Invert dict
{v:k for k,v in {'a':1,'b':2}.items()}
# 42. Merge two dicts
{**{'a':1}, **{'b':2}}
# 43. Count frequency
{x: [1,2,2,3].count(x) for x in set([1,2,2,3])}
# 44. Dict from two lists
dict(zip(['a','b'], [1,2]))
# 45. Defaultdict grouping
from collections import defaultdict; d=defaultdict(list); [d[len(s)].append(s) for s in ['hi','hello','hey']]
# 46. Dict comprehension with condition
{x: x**2 for x in range(5) if x%2 == 0}
# 47. Sort dict by values
dict(sorted({'a':3,'b':1}.items(), key=lambda item: item[1]))
# 48. Nested dict
{'outer': {'inner': 42}}
# 49. Access safely
d.get('missing', 'default')
# 50. Swap keys and values
dict(map(reversed, {'a':1,'b':2}.items()))
File Handling & I/O
# 51. Read lines
open("file.txt").read().splitlines()
# 52. Word count
len(open("file.txt").read().split())
# 53. Write list to file
open("out.txt", "w").writelines([f"{i}\n" for i in range(5)])
# 54. File size
import os; os.path.getsize("file.txt")
# 55. Check file exists
os.path.exists("file.txt")
# 56. Count specific word
open("file.txt").read().count("Python")
# 57. Read last line
open("file.txt").readlines()[-1]
# 58. Read first 100 characters
open("file.txt").read(100)
# 59. Get file extension
os.path.splitext("file.txt")[1]
# 60. Count lines
sum(1 for _ in open("file.txt"))
Searching and Filtering
# 61. First even number
next(x for x in [1,3,5,6] if x%2==0)
# 62. Any true?
any([0, False, 1])
# 63. All positive?
all(x > 0 for x in [1, 2, 3])
# 64. Index of item
[1,2,3].index(2)
# 65. Most frequent
max(set([1,1,2]), key=[1,1,2].count)
# 66. Find longest string
max(["hi", "hello", "world"], key=len)
# 67. Filter None
list(filter(None, [0, "", None, 5]))
# 68. Count even numbers
sum(1 for x in range(10) if x%2 == 0)
# 69. First negative number
next((x for x in [-1, 0, 1] if x < 0), None)
# 70. Filter by type
[x for x in [1, "two", 3.0] if isinstance(x, int)]
Utility Patterns
# 71. Swap
a, b = b, a
# 72. Ternary
"Yes" if x > 0 else "No"
# 73. Chain comparisons
5 < x < 10
# 74. CSV string
",".join(map(str, [1,2,3]))
# 75. Timer
import time; start=time.time(); time.sleep(1); print(time.time()-start)
# 76. Assert in one line
assert x > 0, "x must be positive"
# 77. Retry logic
any(f(x) for _ in range(3))
# 78. Range as list
list(range(5))
# 79. Current timestamp
import time; time.time()
# 80. Generate UUID
import uuid; str(uuid.uuid4())
Functions & Lambdas
# 81. Lambda square
lambda x: x**2
# 82. Compose
f = lambda x: x+1; g = lambda x: x*2; compose = lambda x: f(g(x))
# 83. Map uppercase
list(map(str.upper, ['a','b','c']))
# 84. Filter empty strings
list(filter(None, ["", "hi", ""]))
# 85. Recursive factorial
lambda n: 1 if n==0 else n*factorial(n-1)
# 86. Function call timing
(lambda f: (time.time(), f(), time.time()))(lambda: sum(range(10**6)))
# 87. Inline function call
(lambda x: x**2)(4)
# 88. Conditional lambda
(lambda x: "even" if x%2==0 else "odd")(5)
# 89. Sum lambda
sum(map(lambda x: x+1, range(5)))
# 90. Dict of lambdas
ops = {'add': lambda x, y: x+y, 'mul': lambda x, y: x*y}
Miscellaneous One-Liners
# 91. Python version
import sys; sys.version.split()[0]
# 92. Convert list to int
int("".join(map(str, [1,2,3])))
# 93. Shuffle list
import random; random.shuffle(lst)
# 94. Reverse dict
dict(reversed(list(d.items())))
# 95. Random choice
random.choice([1,2,3])
# 96. Regex match
import re; bool(re.match(r"\d+", "123abc"))
# 97. List to set to list
list(set([1,2,2,3]))
# 98. Terminal progress bar
print(f"\rProgress: [{'='*x}>{' '*(10-x)}]", end='')
# 99. Get memory size
import sys; sys.getsizeof([1,2,3])
# 100. One-liner HTTP server
# Terminal: python -m http.server 8000
Final Thoughts
Python one-liners aren’t just clever — they’re a testament to the elegance and power of the language. Learning to write concise code makes you a better problem solver and forces you to think in terms of composition, transformation, and readability.
Try sprinkling these into your projects or during code challenges. You’ll not only save time — you’ll impress your peers and sharpen your Pythonic thinking.
What’s Your Favorite One-Liner?
Share it in the comments or bookmark this list for your future projects!
Because in Python, less truly is more.