DS DevShelfHub Projects · AI tools
Articles / 10 Python One-Liners Every Engineer Should Actually Use

AI Engineering

10 Python One-Liners Every Engineer Should Actually Use

By DevShelfHub

Ten idiomatic Python one-liners worth memorising — flatten nested lists, swap variables in place, read files with splitlines, count with Counter, reverse with slicing, inline ternaries, chained comparisons, str.join, pprint for nested data, and a Python Easter egg worth knowing. The everyday patterns that quietly separate beginner code from senior code.

10 Python One-Liners Every Engineer Should Actually Use

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.

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

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():

Python
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:

Python
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:

Python
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:

Python
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:

Python
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:

Python
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:

Python
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:

Python
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 of str.join — quadratic time on long strings.
  • Forgetting that Counter returns a dict subclass, so list(counter) gives keys, not (key, count) pairs.
  • Nesting ternaries past one level — the moment your reader has to count parentheses, switch to an if block.
  • 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 collections module — Counter, defaultdict, deque, OrderedDict — before you reach for a third-party library.
  • itertools is the other gem: chain, groupby, combinations, accumulate all replace ten-line loops.
  • Use pathlib.Path over os.path for 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.print is a drop-in upgrade over pprint with 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 specializationPostgres TimescaleDB time-series fix

10 Python One-Liners Every Engineer Should Actually Use FAQ

Are one-liners actually pythonic?

The pythonic ones are. List comprehensions, tuple swaps, and ternaries are explicitly endorsed by the language. The unpythonic version is jamming everything into one expression for the bragging rights. If you can read it back in three months, it’s fine.

When should I use a generator instead of a list comprehension?

When you only need to iterate once and the data is large. Swap [ ] for ( ) and you have a generator: sum(x*x for x in range(10**8)) doesn’t build the list in memory.

Why does splitlines() beat split on newline character?

Two reasons: it handles every newline convention (\n, \r\n, \r) automatically, and it doesn’t leave a trailing empty string when the file ends in a newline. Cleaner result, no edge case.

Is Counter faster than a dict loop?

Yes — it’s implemented in C under the hood. For large sequences the difference is noticeable; for short ones it’s the same speed but much cleaner code.

What’s the rule of thumb for nesting comprehensions?

One nested loop is fine. Two with a filter is the upper edge. Beyond that, expand. The point of a comprehension is brevity with clarity; once it stops being clear, it’s costing you.

Does pprint work on Pydantic models or dataclasses?

Yes — both implement __repr__ sensibly, so pprint indents them cleanly. For very deep nested models, set depth to avoid wall-of-text output.

Any one-liners I should NOT use?

Anything involving lambdas inside reduce for non-trivial logic, or chained map/filter calls that a comprehension would express more clearly. Also avoid exec and eval one-liners on anything that touches user input.