5 Python One-Liners That Replace 20+ Lines of Code
Most beginners write 20 lines when 1 will do. Here are 5 Python one-liners I use daily:
1. Flatten a nested list
flat = [item for sub in nested for item in sub]
2. Count word frequency
from collections import Counter; freq = Counter(text.split())
3. Swap two variables
a, b = b, a
4. Read a file into a list
lines = open('file.txt').read().splitlines()
5. Filter + transform in one step
result = [x**2 for x in nums if x > 0]
These aren't tricks — they're how experienced devs actually write Python.
I've put together a full cheat sheet with 50+ patterns like this inside CodeVault. The free preview gives you access to sample notebooks and the community chat where we break down stuff like this daily.
Stop writing code the hard way. 🔥
