Skip to content

Python one-liners worth knowing

Beginner-friendly · 12 min · every example runs

Good Python is often shorter — not because it's clever, but because the language already has a tool for the job. Each trick below replaces a few lines of loop code with something clearer. Every example prints its result (# →).

Jump to: Lists · Dictionaries · Strings & f-strings · Conditions · Handy tools · When not to


Lists and loops

1. List comprehension — build a list in one line

words = ["RAG", "agents", "LLM", "embeddings"]

# Instead of: result = []; for w in words: if len(w) > 3: result.append(w.lower())
long_words = [w.lower() for w in words if len(w) > 3]
print(long_words)                       # → ['agents', 'embeddings']

Read it as "give me w.lower() for each w in words, if len(w) > 3".

2. enumerate — loop with a counter

chunks = ["Refunds within 30 days.", "Free shipping over ₹500."]
for i, chunk in enumerate(chunks, start=1):   # no more range(len(chunks))
    print(f"[{i}] {chunk}")
# → [1] Refunds within 30 days.
# → [2] Free shipping over ₹500.

3. zip — loop over two lists together

sources = ["faq.md", "policy.md"]
scores = [0.91, 0.42]
for source, score in zip(sources, scores, strict=True):
    print(source, score)
# → faq.md 0.91
# → policy.md 0.42

print(dict(zip(sources, scores, strict=True)))   # → {'faq.md': 0.91, 'policy.md': 0.42}

strict=True (Python 3.10+) raises an error if the lists have different lengths — without it, zip silently stops at the shorter list and you lose data without noticing.

4. Unpacking — take values apart

first, *rest = [10, 20, 30, 40]
print(first, rest)                      # → 10 [20, 30, 40]

a, b = 1, 2
a, b = b, a                             # swap without a temporary variable
print(a, b)                             # → 2 1

5. Slicing — first, last, reversed, every other

items = [1, 2, 3, 4, 5, 6]
print(items[:3], items[-2:])            # → [1, 2, 3] [5, 6]
print(items[::-1])                      # → [6, 5, 4, 3, 2, 1]
print(items[::2])                       # → [1, 3, 5]

6. Flatten a list of lists

batches = [["a", "b"], ["c"], ["d", "e"]]
flat = [item for batch in batches for item in batch]   # read left to right, like nested loops
print(flat)                             # → ['a', 'b', 'c', 'd', 'e']

7. Split a list into batches (for API calls)

texts = ["t1", "t2", "t3", "t4", "t5"]
size = 2
batches = [texts[i:i + size] for i in range(0, len(texts), size)]
print(batches)                          # → [['t1', 't2'], ['t3', 't4'], ['t5']]

Embedding APIs accept many texts per request — batching like this makes far fewer calls. (Python 3.12+ also has itertools.batched(texts, 2).)

8. Remove duplicates but keep the order

ids = ["b", "a", "b", "c", "a"]
print(list(dict.fromkeys(ids)))         # → ['b', 'a', 'c']
print(sorted(set(ids)))                 # → ['a', 'b', 'c']   (set loses the order, so sort it)

Dictionaries

9. Dict comprehension

prices = {"gpt-4o-mini": 0.15, "gpt-4o": 2.50, "llama-3.1-8b": 0.05}
cheap = {model: price for model, price in prices.items() if price < 1}
print(cheap)                            # → {'gpt-4o-mini': 0.15, 'llama-3.1-8b': 0.05}

10. .get() with a default — no KeyError

config = {"model": "gpt-4o-mini"}
print(config.get("temperature", 0.2))   # → 0.2

11. Merge dictionaries

defaults = {"model": "gpt-4o-mini", "temperature": 0.2}
overrides = {"temperature": 0.7}
settings = defaults | overrides         # the right-hand side wins
print(settings)                         # → {'model': 'gpt-4o-mini', 'temperature': 0.7}

12. Sort a dictionary by value

scores = {"faq.md": 0.42, "policy.md": 0.91, "blog.md": 0.10}
best = sorted(scores, key=scores.get, reverse=True)
print(best[:2])                         # → ['policy.md', 'faq.md']

Strings and f-strings

13. f-string debugging with =

model, tokens = "gpt-4o-mini", 1834
print(f"{model=}, {tokens=}")           # → model='gpt-4o-mini', tokens=1834

The fastest way to see what a variable holds — it prints the name and the value.

14. Format numbers

cost = 1234.5678
print(f"₹{cost:,.2f}")                  # → ₹1,234.57
print(f"{0.8734:.1%}")                  # → 87.3%
print(f"{7:03d}")                       # → 007

15. Join a list into one string

tags = ["rag", "agents", "llm"]
print(", ".join(tags))                  # → rag, agents, llm

16. Clean up messy whitespace

messy = "  Retrieval   augmented \n generation  "
print(" ".join(messy.split()))          # → Retrieval augmented generation

Conditions

17. Conditional expression

score = 0.72
label = "relevant" if score >= 0.5 else "ignore"
print(label)                            # → relevant

18. any / all — check a whole list at once

answers = ["ok", "", "fine"]
print(any(a == "" for a in answers))    # → True    at least one empty answer
print(all(len(a) > 0 for a in answers)) # → False   not every answer has text

19. Chained comparison

temperature = 0.7
print(0 <= temperature <= 2)            # → True    instead of: 0 <= t and t <= 2

20. The walrus operator := — assign and test in one go

import re

text = "Order #4821 was refunded."
if (match := re.search(r"#(\d+)", text)):
    print(match.group(1))               # → 4821

It shines in loops like while (line := file.readline()): and in chat loops: while (question := input("> ")):.


Handy standard-library tools

21. Counter — count anything

from collections import Counter

words = "rag agents rag llm rag agents".split()
print(Counter(words).most_common(2))    # → [('rag', 3), ('agents', 2)]

22. defaultdict — group items without checking keys

from collections import defaultdict

chunks = [("faq.md", "c1"), ("policy.md", "c2"), ("faq.md", "c3")]
by_source = defaultdict(list)
for source, chunk in chunks:
    by_source[source].append(chunk)     # no "if source not in by_source" needed
print(dict(by_source))                  # → {'faq.md': ['c1', 'c3'], 'policy.md': ['c2']}

23. max / sorted with key

hits = [{"source": "a.md", "score": 0.4}, {"source": "b.md", "score": 0.9}]
print(max(hits, key=lambda h: h["score"])["source"])    # → b.md

24. pathlib — find files in one line

from pathlib import Path

md_files = sorted(p.name for p in Path(".").glob("*.md"))   # every .md file in this folder
print(type(md_files).__name__)          # → list

Use rglob("*.md") to search sub-folders too.

25. functools.cache — remember expensive results

from functools import cache

@cache
def embed(text):
    print(f"computing {text!r}")        # only printed the first time
    return len(text)                    # pretend this is a slow API call

embed("hello")                          # → computing 'hello'
embed("hello")                          # (nothing printed — the result came from the cache)
print(embed.cache_info().hits)          # → 1

When NOT to use a one-liner

A one-liner is good when it's easier to read than the loop. Stop when it isn't:

data = [{"s": 0.9, "t": "a"}, {"s": 0.2, "t": "b"}, {"s": 0.7, "t": "c"}]
out = {d["t"]: round(d["s"] * 100) for d in sorted([x for x in data if x["s"] > 0.5], key=lambda x: -x["s"])}
print(out)                              # → {'a': 90, 'c': 70}
data = [{"s": 0.9, "t": "a"}, {"s": 0.2, "t": "b"}, {"s": 0.7, "t": "c"}]
relevant = [d for d in data if d["s"] > 0.5]
relevant.sort(key=lambda d: d["s"], reverse=True)
percentages = {d["t"]: round(d["s"] * 100) for d in relevant}
print(percentages)                      # → {'a': 90, 'c': 70}

Rules of thumb: one condition is fine; nested comprehensions with conditions are not. If you need a comment to explain it — split it up. More in Write clean, readable code.

Practice

  • Turn result = [] + for + append loops in your own code into comprehensions.
  • Use Counter to find the 3 most common words in a paragraph.
  • Add f"{variable=}" prints instead of print(variable) next time you debug.

Next: Handle LLM API errors →