Introduction
Python is famous for letting you do in one line what other languages need ten for. The catch is that most beginners pick up the syntax and then never use the parts of the language that pay rent — list comprehensions, the standard library, the slicing tricks, the small set of idioms that quietly separate “writes Python” from “writes good Python.”
Here are ten one-liners that are useful daily, idiomatic, and tiny enough to remember. Drop these in place of the five-line versions you’re currently writing, and your code reads cleaner the same afternoon.
📚 Table of contents
- 1. Flatten a nested list
- 2. Swap variables in place
- 3. Read a file into a list of lines
- 4. Count frequencies with Counter
- 5. Reverse a string (or anything iterable)
- 6. Inline conditional assignment
- 7. Chained comparisons
- 8. Join any iterable into a delimited string
- 9. Pretty-print nested structures with pprint
- 10. A Python Easter egg worth knowing about
- Common mistakes
- Pro tips
- Frequently asked questions
1. Flatten a nested list
Got a list of lists? Flatten it without an import.
flat = [item for sub in nested for item in sub]
This is a list comprehension with two for clauses. The outer loop walks each sub-list; the inner loop pulls every item out. Works on uneven shapes too — rows of different lengths, mixed types, any iterable you can loop over. Compared to the standard four-line nested loop, you save three lines and one temporary variable.
2. Swap variables in place
The classic three-line swap with a temp variable is muscle memory in most languages. Not in Python.
a, b = b, a
Tuple packing and unpacking. Works for any pair of names, including list elements
(arr[0], arr[-1] = arr[-1], arr[0]), dictionary values, and chained multi-way swaps
(a, b, c = c, a, b). The right side is evaluated first, so there’s no risk of
clobbering.
3. Read a file into a list of lines
The version everyone writes splits on \n and then loops to strip trailing whitespace. The
cleaner version uses splitlines():
lines = Path("data.txt").read_text().splitlines()
splitlines() handles every newline convention (\n, \r\n,
\r), strips the trailing newline characters, and returns a clean list. Great for config
files, log files, simple CSVs. For production code with large files, use a context manager —
with open(...) as f: — but the one-liner is perfect for scripts and notebooks.
4. Count frequencies with Counter
Stop writing the for x in seq: counts[x] = counts.get(x, 0) + 1 pattern. Use
Counter from the standard library:
from collections import Counter
freq = Counter("the cat sat on the mat".split())
freq.most_common(2) # [('the', 2), ('cat', 1)]
Counter behaves like a dict but adds frequency-specific methods: most_common(n)
for top-n, arithmetic operators (Counter("aab") + Counter("abc")),
and elements() to expand back into a sequence. The collections module is
full of these — defaultdict, deque, OrderedDict —
and most of them save you boilerplate.
5. Reverse a string (or anything iterable)
The [::-1] slice reverses any sequence — string, list, tuple, bytes:
reversed_str = "hello"[::-1] # 'olleh'
is_palindrome = word == word[::-1]
The slice syntax is [start:stop:step]. Leaving start and stop blank with a step of
-1 means “walk the whole thing backwards.” A nice side benefit: the same
trick checks palindromes in one line.
6. Inline conditional assignment
Python’s ternary expression reads almost like English:
parity = "even" if x % 2 == 0 else "odd"
display = score if score <= 100 else "100+"
The pattern is value_if_true if condition else value_if_false. Best used for short
expressions and clamping values. Doubles up nicely inside list comprehensions:
[x if x > 0 else 0 for x in xs]. Don’t nest more than once — if you reach
for a second level, expand to an if/elif/else block.
7. Chained comparisons
Python lets you write the maths-textbook form of a range check:
if 1 < x < 10:
...
if 0 <= i < len(arr):
...
Equivalent to 1 < x and x < 10, but shorter and easier to read. Python evaluates
x only once even though it appears twice in the expression. Works with any comparison
operators: a < b <= c, a == b == c for equality, and so on.
8. Join any iterable into a delimited string
Concatenating with + in a loop is the slow, ugly way. str.join is the
idiomatic one:
csv = ", ".join(map(str, [1, 2, 3, 4])) # '1, 2, 3, 4'
piped = " | ".join(["alpha", "beta", "gamma"])
The delimiter is the string on the left; join takes the iterable. map(str, ...)
converts non-string items before joining — without it, mixed-type lists raise TypeError.
For lists that are already strings, drop the map.
9. Pretty-print nested structures with pprint
Printing a deeply nested dict or list with print gives you one unreadable line. The
pprint module exists for exactly this:
from pprint import pprint
pprint(data, depth=3, width=120, compact=False)
Indented output, configurable depth so you don’t drown in a 12-layer JSON response, and a
width argument for terminal wrapping. Essential when debugging API responses, config
files, or anything with structure. Pair with json.dumps(data, indent=2) when you need
valid JSON instead of Python repr.
10. A Python Easter egg worth knowing about
Not technically a productivity tip, but it deserves a place on the list because every Python developer should know it exists:
from __future__ import braces
# SyntaxError: not a chance
Guido’s explicit answer to anyone hoping Python will adopt curly braces for blocks. There are a
few more: import this prints the Zen of Python, import antigravity opens
an xkcd comic, and import __hello__ still works as a leftover from very old Python
versions. They’re harmless. They’re also a small reminder that the language has
opinions.
❌ Common mistakes
- Cramming three nested comprehensions onto one line because you can. Readability matters more than line count.
- Using
+in a loop instead ofstr.join— quadratic time on long strings. - Forgetting that
Counterreturns a dict subclass, solist(counter)gives keys, not (key, count) pairs. - Nesting ternaries past one level — the moment your reader has to count parentheses, switch to an
ifblock. - Reading large files into memory with
read_text().splitlines()instead of streaming. - Using mutable defaults in function signatures — not a one-liner trick, but it gets every Python beginner once.
💡 Pro tips
- Learn the
collectionsmodule —Counter,defaultdict,deque,OrderedDict— before you reach for a third-party library. itertoolsis the other gem:chain,groupby,combinations,accumulateall replace ten-line loops.- Use
pathlib.Pathoveros.pathfor filesystem work — cleaner, chainable, modern. - When a one-liner gets longer than 80 characters, expand it. Compression isn’t the goal; clarity is.
- For ad-hoc debugging,
rich.printis a drop-in upgrade overpprintwith colour and table support.
Conclusion
Ten one-liners, all standard library, all worth using in real code. List comprehensions, tuple swap,
splitlines, Counter, slice reversal, the inline ternary, chained
comparisons, str.join, and pprint — pick the three you didn’t
know and try them on your next script. The compound effect on readable code is real.
Most “senior Python developer” signals are this kind of thing: not exotic features, just using the idiomatic version of the everyday pattern.
Related reading: learn Python in 2026: zero to specialization — Postgres TimescaleDB time-series fix