10 Python One-Liners That Save Hours
By My Code Diary
I used to be the person who wrote 12 lines of code to do something Python could do in one.
Not because I was lazy. Because I simply didn’t know. And honestly, that’s the worst kind of inefficiency — the kind you don’t even realize is costing you time until someone slides over and rewrites your entire function on a sticky note.
That moment happened to me three years ago. A senior dev looked at my 40-line CSV parsing script, smiled politely, and typed a single line. It ran faster, looked cleaner, and I wanted to close my laptop and go into farming.
Instead, I went home and spent a weekend learning Python’s hidden depth. What follows are 10 one-liners I’ve collected since then — each one earned through frustration, curiosity, or mild embarrassment. They cover automation, data handling, file ops, and everyday programming headaches.
These aren’t party tricks. Every line here has saved me real hours on real projects.
1. Flatten a Nested List Without Importing Anything
You’ve got a list of lists. Maybe from a database query, maybe from scraping. You need it flat. Most people reach for a loop.
flat = [item for sublist in nested for item in sublist]
Clean. No imports. Works in every Python version you’re realistically using. The double for in a single comprehension trips people up at first, but once it clicks, you’ll use it everywhere.
2. Read a File Into a List in One Line
lines = open("data.txt").read().splitlines()
No with block, no strip loop, no extra variable. Every line is a clean string in a list. Is it the most production-safe approach? Use with in prod. But for scripting and quick data wrangling? This is the one.
3. Swap Two Variables Without a Temp Variable
a, b = b, a
This one is almost embarrassingly simple. But I watched a junior dev write a three-line swap with a temp variable last year, and I realized we don’t talk about this enough. Python’s tuple unpacking makes this native. No tricks, no hacks.
4. Count Element Frequencies in a List
The manual way involves a loop and a dictionary. The Python way:
from collections import Counter; freq = Counter(my_list)
Counter returns a dictionary-like object where keys are elements and values are counts. It also has a .most_common(n) method that returns the top n elements. I’ve used this in log parsing, text analysis, and user behavior tracking.
5. Merge Two Dictionaries (Python 3.9+)
merged = dict_a | dict_b
Before 3.9, this required {**dict_a, **dict_b}. The | operator is cleaner and more readable. If keys overlap, dict_b wins. This comes up constantly when combining config files or API responses.
6. Filter a List Based on a Condition
evens = list(filter(lambda x: x % 2 == 0, numbers))
Or, if you prefer comprehension style:
evens = [x for x in numbers if x % 2 == 0]
Both work. The comprehension version tends to read more naturally. I use filter() when I’m chaining it with other functional operations — it slots in cleanly.
7. Run a Simple HTTP Server From Any Directory
This one isn’t code you write — it’s a command you run. But it belongs in this list because I use it at least twice a week.
python -m http.server 8000
Instant file server. Serves everything in the current directory over localhost:8000. I use this to preview HTML exports, share files across devices on the same network, and test static sites without spinning up anything. Massively underused.
8. Get All Unique Values From a List
unique = list(set(my_list))
Dead simple. set() removes duplicates, list() brings it back to a list. The caveat: sets don’t preserve order. If order matters, use:
unique = list(dict.fromkeys(my_list))
This preserves insertion order while removing duplicates. I switched to this pattern once I started caring about reproducibility in data pipelines.
9. Sort a List of Dictionaries by a Key
sorted_data = sorted(records, key=lambda x: x['date'])
If you’ve ever had a list of API responses or database rows you needed sorted by a field, this is the pattern. Add reverse=True to flip the order. You can also sort by multiple keys using a tuple:
sorted_data = sorted(records, key=lambda x: (x['category'], x['date']))
I use this constantly when preparing data before visualization or reporting.
10. Run a One-Off Shell Command and Capture Its Output
import subprocess; output = subprocess.check_output("ls -la", shell=True).decode()
Pro Tip: For production-grade automation, use
subprocess.run()withcapture_output=Trueand avoidshell=Truewhen possible — it’s a security consideration when input isn’t controlled.
This is the gateway to automating your entire operating system with Python. I’ve used this to build scripts that rename files in bulk, trigger builds, check disk usage, and restart services — all from within a Python workflow. Once you know you can call shell commands inline, a huge class of automation becomes suddenly reachable.
The Real Takeaway
None of these one-liners are magic. They’re just Python doing what Python was designed to do — readable, expressive, and efficient.
The problem is that most of us learn Python from tutorials that teach us the long way first and never come back around to show the short way. We build habits early, and those habits are hard to shake.
“The best code is the code you don’t have to write.” — Jeff Atwood
My advice: don’t collect these like trading cards. Pick two or three that solve problems you face right now. Use them until they’re muscle memory. Then come back for more.
The senior dev who rewrote my CSV parser didn’t have a better brain. He just had more reps. You can get there faster — you just have to know what to practice.
Drop the one-liner that surprised you most in the comments.
My Code Diary publishes practical Python content for developers who want to stop writing code the slow way.



