CoreMesh

Useful Python One Liners and When Not to Use Them

Terminal one-liners that save real time, in-code idioms worth knowing, runnable examples, and the traps that make a short line the wrong choice.

Checked against the official docs on Oct 24, 2026.

Useful Python One Liners and When Not to Use Them

The most useful Python one-liners run straight from a terminal: python -m json.tool data.json validates and pretty-prints JSON, python -m http.server shares the current folder over HTTP, and python -c "import secrets; print(secrets.token_urlsafe(32))" prints a random token. Inside code, comprehensions and a few built-ins cover most one-line jobs. Below are the ones worth memorizing, with runnable examples and the cases where a one-liner is the wrong tool.

Command-line one-liners cheat sheet

Many standard library modules double as small command-line tools when you run them with python -m. These are the everyday ones, with the version that introduced each where it matters:

Command What it does Version
python -m json.tool data.json Validates and pretty-prints a JSON file Any Python 3
python -m json data.json Same tool, shorter name 3.14+
python -m http.server Shares the current folder over HTTP Any Python 3
python -m http.server -H Cache-Control no-store Same, with a custom response header 3.15+
python -c "import secrets; print(secrets.token_urlsafe(32))" Prints a URL-safe random token Any current Python
python -m uuid Prints a UUID 3.12+
python -m sqlite3 app.db Opens a SQLite shell on a database file 3.12+
python -m venv .venv Creates a virtual environment Any current Python
python -m unittest --durations=3 Runs tests and lists the 3 slowest 3.12+

On Windows, use py in place of python if that's how you launch Python; on macOS and many Linux systems the command is python3. Because these tools ship with Python itself, they work on any machine that has Python installed, including CI runners and containers, with nothing to pip install first.

The version notes come from the official release notes. What's New in Python 3.12 records the new command-line interfaces for sqlite3 and uuid, and the --durations option for unittest. What's New in Python 3.15, the current release as of October 2026, lists more modules whose command-line help is now colored, including timeit, zipfile, gzip, random, pdb, doctest, inspect, ast and tokenize. Every one of them accepts --help, which is the fastest way to see its options on your version.

Share a folder with python -m http.server

python -m http.server serves the files in the current directory over HTTP, which makes it the quickest way to preview a static site build or pass a file to another device on your network. It prints the address it's listening on; open that address in a browser, and press Ctrl+C in the terminal to stop it.

bash
cd dist
python -m http.server
python -m http.server --help

Python 3.15 added three things to it, per the release notes: a -H/--header option for custom response headers, a --content-type option that sets the fallback Content-Type for files with unknown extensions, and colored request logging. Run python -m http.server --help to see which options your version supports, including the ones that choose the port and the listening address.

Treat it as a preview tool, not a web host:

  1. There's no login. Anyone who can reach the port can browse every file in the folder, so start it from a folder that holds only what you mean to share.
  2. Stop it as soon as you're done, especially on shared or public Wi-Fi.
  3. Never point it at your home folder or a project with .env files, keys or other secrets.

Pretty-print and validate JSON with json.tool

The JSON module's command-line tool reads a file or standard input, checks that it parses, and prints it indented. When the input is invalid, it prints the parse error with a line and column instead, which makes it a handy validator inside shell scripts.

bash
python -m json.tool settings.json
python -m json.tool --sort-keys --indent 2 settings.json
python -m json.tool --compact settings.json settings.min.json
echo '{"b": 2, "a": 1}' | python -m json.tool --sort-keys

According to the json module reference, the full option set is --sort-keys, --no-ensure-ascii, --json-lines for one document per line, and one of --indent, --tab, --no-indent or --compact. An optional second filename writes the result there instead of the terminal.

Because the tool exits with an error status on invalid input, it slots straight into shell loops and CI checks. This one reports every broken file in a folder:

bash
for f in config/*.json; do python -m json.tool "$f" > /dev/null || echo "invalid: $f"; done

The parse error itself goes to standard error, so you still see the line and column for each failure. Since Python 3.14 you can type python -m json instead; python -m json.tool keeps working everywhere.

Generate tokens, passwords and IDs

The Python standard library index sums up the difference in two lines: secrets generates secure random numbers for managing secrets, while random generates pseudo-random numbers. Anything that protects access, such as API keys, password reset links or session tokens, should come from secrets. From the terminal:

bash
python -c "import secrets; print(secrets.token_urlsafe(32))"
python -c "import secrets; print(secrets.token_hex(16))"
python -c "import uuid; print(uuid.uuid4())"

The same functions inside a script, printing only the shape of each value:

python
import secrets
import string
import uuid

token = secrets.token_urlsafe(32)        # 32 random bytes, URL-safe text
hex_key = secrets.token_hex(16)          # 16 random bytes as 32 hex digits
alphabet = string.ascii_letters + string.digits
password = "".join(secrets.choice(alphabet) for _ in range(16))

# Print only the shape: never reuse a secret you've seen printed somewhere
print("token_urlsafe(32):", len(token), "chars, starts", token[:4] + "...")
print("token_hex(16):    ", len(hex_key), "hex digits")
print("16-char password: ", len(password), "chars, alphanumeric:", password.isalnum())
print("uuid4 version:    ", uuid.uuid4().version)
print("compare_digest:   ", secrets.compare_digest(hex_key, hex_key))

The number you pass is a count of random bytes, not characters, which is why 32 bytes become 43 URL-safe characters and 16 bytes become 32 hex digits. Pass an explicit size whenever the length matters, for example when a database column has a fixed width. To check a token a user sends back, compare it with secrets.compare_digest() rather than ==.

Quick python -c recipes

python -c runs the code you pass as a string and exits. Wrap the code in double quotes on macOS and Linux shells and use single quotes inside it, separate simple statements with semicolons, and reach for a comprehension or generator expression where you'd otherwise need a loop. Some recipes that come up all the time:

bash
python -c "import sys; print(sys.version)"                   # exact interpreter version
python -c "import json; print(json.__file__)"                # where a module is loaded from
python -c "import sys; print(sys.prefix != sys.base_prefix)" # True inside a virtual environment
python -c "import ssl; print(ssl.OPENSSL_VERSION)"           # OpenSSL your Python links against
printf '1.5\n2\n3.25\n' | python -c "import sys; print(sum(float(line) for line in sys.stdin))"

The last one shows the pattern for quick data jobs: pipe text in and read sys.stdin line by line, which is handy for summing a column you've already cut out of a log. Once the logic needs more than one expression, save it as a .py file instead. And when a module already has a command-line interface, prefer python -m module over a hand-written -c snippet: it's shorter and already handles the edge cases.

In-code one-liners worth knowing

Comprehensions and a few built-ins replace most small loops. Every line here is plain standard library Python:

python
from collections import Counter
from itertools import batched

nums = [5, 3, 8, 3, 9, 1, 8]
words = "the cat and the hat and the bat".split()
users = [{"name": "Ada", "age": 36}, {"name": "Linus", "age": 28}, {"name": "Grace", "age": 45}]

print([n * n for n in nums if n % 2])                    # filter + map
print({w: len(w) for w in ["cat", "zebra"]})             # dict comprehension
print(list(dict.fromkeys(nums)))                         # dedupe, keep order
print(Counter(words).most_common(2))                     # top items
print(sorted(users, key=lambda u: u["age"])[0]["name"])  # youngest
print(max(users, key=lambda u: u["age"])["name"])        # oldest
print([x for row in [[1, 2], [3], [4, 5]] for x in row]) # flatten one level
print(list(zip(*[[1, 2, 3], [4, 5, 6]])))                # transpose
print(list(batched(range(7), 3)))                        # chunks (3.12+)
print({v: k for k, v in {"a": 1, "b": 2}.items()})       # invert a dict
print({"a": 1, "b": 2} | {"b": 3, "c": 4})               # merge, right wins
print(any(n > 8 for n in nums), all(n > 0 for n in nums))
print(sum(1 for w in words if w == "the"))               # count matches

A few notes. dict.fromkeys() removes duplicates and, as the output shows, keeps the first-seen order. itertools.batched() arrived in Python 3.12 and collects items into tuples where the last one may be shorter. With the | merge, the right-hand value wins when both sides share a key. Generator expressions inside sum(), any() and all() don't build a list first, and any() and all() stop as soon as the answer is known.

Unpacking in comprehensions in Python 3.15

Python 3.15 adds PEP 798, which lets comprehensions and generator expressions unpack with * and **. The release notes present it as a direct alternative to nested comprehensions and itertools.chain():

python
lists = [[1, 2], [3, 4], [5]]
print([*L for L in lists])        # [1, 2, 3, 4, 5]

dicts = [{"a": 1}, {"b": 2}, {"a": 3}]
print({**d for d in dicts})       # {'a': 3, 'b': 2}

On Python 3.14 and older this is a SyntaxError, so keep the nested for form in code that has to run on earlier versions.

When not to use a one-liner

A one-liner earns its place when it's shorter and just as clear as the loop it replaces. These are the cases where it isn't:

python
# One-liners that look fine and aren't
grid = [[0] * 3] * 3            # three references to ONE list
grid[0][0] = 1
print("aliased grid:", grid)
grid = [[0] * 3 for _ in range(3)]
grid[0][0] = 1
print("fixed grid:  ", grid)

callbacks = [lambda: i for i in range(3)]          # late binding
print("late binding:", [f() for f in callbacks])
callbacks = [lambda i=i: i for i in range(3)]
print("bound early: ", [f() for f in callbacks])

shared = dict.fromkeys(["a", "b"], [])              # one list shared by every key
shared["a"].append(1)
print("fromkeys:    ", shared)
print("comprehension:", {k: [] for k in ["a", "b"]})

result = [3, 1, 2].sort()                           # sorts in place, returns None
print("list.sort():", result, "| sorted():", sorted([3, 1, 2]))

Each bug comes from the same place: a compact expression hides that several names point at one object, or that a value is looked up later than you think. Beyond these traps, skip the one-liner when:

  1. It needs a second read. Nested comprehensions with two for clauses and an if are where readability usually breaks. Write the loop.
  2. It has side effects. A comprehension that calls print() or appends to another list builds a throwaway list. Use a for loop.
  3. Errors need handling. There's no try inside a comprehension, so one bad item crashes the whole line.
  4. It goes to production. python -m http.server is for previews and quick transfers, not for serving real traffic.
  5. You're guessing about speed. A one-liner isn't automatically faster than the loop it replaces. Measure both before trading readability for a few microseconds.
  6. It touches secrets. Commands with tokens or passwords typed on the command line can end up in your shell history. Generate them in a script or read them from an environment variable instead.

For more references in the same compact style, browse the cheat sheets. When a dense one-liner from someone else's code needs unpacking, the explain code line by line prompt helps.

Quick answers

Which Python modules can I run with python -m?

Any module that has a command-line interface. The Python 3.15 release notes list ast, compileall, doctest, gzip, inspect, json.tool, pdb, random, sqlite3, timeit, tokenize, trace, unittest, uuid, zipapp and zipfile among them, and python -m module --help shows each one's options.

Can I write an if/else in a Python one-liner?

Yes, as a conditional expression: python -c "n = 7; print('odd' if n % 2 else 'even')". A full if statement also works on one line on its own, but not after a semicolon.

Can I use a for loop with python -c?

Yes, as long as the loop starts the command, as in python -c "for i in range(3): print(i)". Putting it after an import and a semicolon is a syntax error; use a comprehension or a multi-line command instead.

Are list comprehensions faster than for loops?

For building a list they are often somewhat faster than a loop that calls append, but the gap depends on the work inside. Measure your own case with the timeit module and keep the more readable version when the difference is small.

Indra Wijaya

Builds and runs small AI-assisted tools and writes up what works: Claude Code, AI APIs, everyday coding and the fixes in between.

About CoreMesh