3 min read · 525 words
Python is famous for letting you express complex ideas in just a few lines of code. But some one-liners go beyond clean syntax—they completely change how you think about solving problems.
Whether you're processing data, handling files, or automating tedious workflows, here are 10 Python one-liners that pack a serious punch, plus a bonus look at how to supercharge your Python scripts using the latest Anthropic SDK.
1. Start a Quick Web Server
Need to share files from your current directory instantly? No need to install Express or Flask.
python3 -m http.server 8080
Takeaway: Instantly spins up a static file server in the current directory.
2. Flatten a Nested List
Dealing with deeply nested lists from an API response? Unpack them recursively in one go.
flatten = lambda l: [item for sublist in l for item in (flatten(sublist) if isinstance(sublist, list) else [sublist])]
print(flatten([1, [2, [3, 4], 5], 6])) # [1, 2, 3, 4, 5, 6]
3. Read a File Into a List of Lines (Without Newlines)
Forget .readlines() leaving trailing \n characters everywhere.
lines = [line.strip() for line in open('data.txt')]
4. Transpose a 2D Matrix
Flipping rows and columns is a classic interview problem. Python's zip unpacks it effortlessly.
matrix = [[1, 2, 3], [4, 5, 6]]
transposed = list(map(list, zip(*matrix)))
print(transposed) # [[1, 4], [2, 5], [3, 6]]
5. Simple In-Memory Profiling
Want to measure how long a code block takes without importing timeit boilerplate?
import time; t = time.time(); [i**2 for i in range(10_000_000)]; print(f"Took: {time.time() - t:.4f}s")
6. Remove Duplicates While Preserving Order
set() destroys order. Use dict.fromkeys() to keep things deterministic.
unique_items = list(dict.fromkeys([1, 3, 2, 1, 4, 2]))
print(unique_items) # [1, 3, 2, 4]
7. Merge Two Dictionaries (Python 3.9+)
The merge operator | makes dictionary combination cleaner than ever.
merged = {"a": 1, "b": 2} | {"b": 99, "c": 4}
print(merged) # {'a': 1, 'b': 99, 'c': 4}
8. Generate a Random Password
No external dependencies required for basic string generation.
import random, string
password = "".join(random.choices(string.ascii_letters + string.digits + string.punctuation, k=16))
9. Check if a String is a Palindrome
Strip spaces, lowercase, and compare it reversed in a single slice.
is_palindrome = lambda s: (c := ''.join(s.lower().split())) == c[::-1]
print(is_palindrome("A man a plan a canal Panama")) # True
10. Query Claude Directly from Python
Want to add AI capabilities to your scripts? Here is how to make a clean API call using the current anthropic SDK. Notice how we use claude-opus-5 with adaptive thinking enabled and zero deprecated parameters.
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5",
max_tokens=16000,
thinking={"type": "adaptive"},
output_config={"effort": "medium"},
messages=[{"role": "user", "content": "Explain quantum computing in one sentence."}],
)
for block in response.content:
if block.type == "text":
print(block.text)
Conclusion
One-liners are fantastic for readability and quick scripts, but remember the golden rule of Python: readability counts. Don't sacrifice maintainability just to fit everything onto a single line.
What is your favorite Python one-line trick? Drop it in the comments below!
Top comments (0)