The best code is code you don’t have to write. One-liners aren’t about being clever — they’re about knowing your language deeply enough to express complex operations in minimal, readable form. Here are the most useful Python, JavaScript, and shell one-liners that working developers reach for every day, with explanations of how they actually work.
⚡ TL;DR: These aren’t code golf tricks. Every one-liner here solves a real problem faster than a multi-line approach would — and understanding why they work makes you a better programmer, not just a more concise one.
Python One-Liners That Replace 5+ Lines of Code
1. Swap Two Variables (No Temp Variable)
# Traditional approach — 3 lines, 1 temp variable
temp = a
a = b
b = temp
# ✅ Python one-liner — tuple unpacking
a, b = b, a
# Why it works: Python evaluates the right side completely first,
# creating a tuple (b, a), then unpacks it into a and b.
# No temporary variable, no mutation during evaluation.
# Works for any number of variables:
x, y, z = z, x, y # rotate three values2. Find the Most Common Element in a List
from collections import Counter
data = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
# ✅ One-liner: find mode
most_common = Counter(data).most_common(1)[0][0]
# Result: 'apple'
# Top N most common:
top3 = [item for item, _ in Counter(data).most_common(3)]
# Result: ['apple', 'banana', 'cherry']
# Real use case: find most common HTTP status code in logs
from collections import Counter
status_codes = [int(line.split()[8]) for line in open('access.log') if len(line.split()) > 8]
print(Counter(status_codes).most_common(5))3. Flatten a Nested List
nested = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
# ✅ One-liner using itertools.chain
from itertools import chain
flat = list(chain.from_iterable(nested))
# Result: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Alternative — list comprehension (slightly slower but no import)
flat = [item for sublist in nested for item in sublist]
# For deeply nested (arbitrary depth):
import json
flat_deep = json.loads(str(nested).replace('[','').replace(']','').split(','))
# Better: use a recursive generator for arbitrary depth4. Merge Dictionaries (Python 3.9+)
defaults = {'timeout': 30, 'retries': 3, 'verbose': False}
overrides = {'timeout': 60, 'debug': True}
# ✅ Python 3.9+ — merge operator
merged = defaults | overrides
# Result: {'timeout': 60, 'retries': 3, 'verbose': False, 'debug': True}
# Right side wins on conflicts
# Python 3.5+ alternative
merged = {**defaults, **overrides}
# In-place update
defaults |= overrides # Python 3.9+5. Group List Items by a Condition
from itertools import groupby
data = [1, 1, 2, 2, 2, 3, 1, 1]
# ✅ Group consecutive identical elements
groups = {k: list(v) for k, v in groupby(data)}
# Result: {1: [1, 1], 2: [2, 2, 2], 3: [3]}
# Group by a property (sort first for groupby to work correctly)
users = [{'name': 'Alice', 'dept': 'Eng'}, {'name': 'Bob', 'dept': 'Sales'}, {'name': 'Carol', 'dept': 'Eng'}]
by_dept = {k: list(v) for k, v in groupby(sorted(users, key=lambda x: x['dept']), key=lambda x: x['dept'])}
# Result: {'Eng': [Alice, Carol], 'Sales': [Bob]}JavaScript One-Liners That Save Real Time
6. Deep Clone an Object Without a Library
const original = { user: { name: 'Alice', scores: [95, 87, 92] } };
// ❌ Shallow copy — nested objects still share reference
const shallow = { ...original };
// ✅ Deep clone — structuredClone (modern, built-in, fast)
const deep = structuredClone(original);
deep.user.name = 'Bob';
console.log(original.user.name); // Still 'Alice' ✓
// structuredClone handles: Dates, Maps, Sets, RegExp, ArrayBuffers
// Does NOT handle: Functions, DOM nodes, class instances
// Older approach (avoid — doesn't handle Dates correctly):
const old = JSON.parse(JSON.stringify(original));7. Remove Duplicates from an Array
const arr = [1, 2, 3, 2, 1, 4, 3, 5];
// ✅ Remove duplicates — Set conversion
const unique = [...new Set(arr)];
// Result: [1, 2, 3, 4, 5]
// Remove duplicate objects by a key
const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 1, name: 'Alice Clone' }];
const uniqueById = [...new Map(users.map(u => [u.id, u])).values()];
// Result: [{ id: 1, name: 'Alice Clone' }, { id: 2, name: 'Bob' }]
// Note: last duplicate wins (Alice Clone, not Alice)8. Safe Optional Chaining with Default Values
const user = { profile: { address: null } };
// ❌ Old way — TypeError crashes if any level is null
const city = user.profile.address.city; // TypeError!
// ✅ Optional chaining — returns undefined instead of throwing
const city = user?.profile?.address?.city;
// Result: undefined (no crash)
// With nullish coalescing for defaults
const city = user?.profile?.address?.city ?? 'Unknown City';
// Result: 'Unknown City'
// Works on method calls too
const len = user?.profile?.getAddressCount?.() ?? 0;9. Generate a Random Hex Color
// ✅ Random hex color in one line
const color = '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0');
// Result: '#a3f2c1' (random each time)
// How it works:
// Math.random() → 0 to 1
// * 0xFFFFFF → 0 to 16777215 (max hex color value)
// .toString(16) → convert to hex string
// .padStart(6, '0') → ensure 6 chars (add leading zeros if needed)
// Generate N unique colors for a chart:
const colors = Array.from({ length: 5 }, () =>
'#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0')
);Shell One-Liners for Terminal Power Users
10. Find and Kill a Process on a Specific Port
# ✅ Kill whatever is running on port 3000 (works on Mac/Linux)
kill -9 $(lsof -ti:3000)
# Safer version — shows what you're killing first
lsof -ti:3000 | xargs -I{} sh -c 'echo "Killing PID: {}" && kill -9 {}'
# Windows equivalent (PowerShell):
# Get-Process -Id (Get-NetTCPConnection -LocalPort 3000).OwningProcess | Stop-Process -Force11. Start an Instant HTTP Server in Any Directory
# Python 3 (built-in, no install needed)
python3 -m http.server 8000
# Serves current directory at http://localhost:8000
# Node.js (if you have npx)
npx serve .
# With CORS headers (useful for local API testing)
python3 -c "
import http.server, socketserver
class Handler(http.server.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_header('Access-Control-Allow-Origin', '*')
super().end_headers()
socketserver.TCPServer(('', 8000), Handler).serve_forever()
"12. Find All Files Modified in the Last 24 Hours
# Find recently modified files — useful for debugging deployments
find . -mtime -1 -type f -not -path '*/node_modules/*' -not -path '*/.git/*'
# With file sizes
find . -mtime -1 -type f | xargs ls -lh
# Find large files (over 100MB) in current directory
find . -size +100M -type f | xargs ls -lh
# Delete all .log files recursively (with confirmation)
find . -name "*.log" -type f -exec rm -i {} ;One-Liners Cheat Sheet
- ✅
a, b = b, a— Python variable swap, no temp - ✅
Counter(list).most_common(1)[0][0]— most frequent element - ✅
[*chain.from_iterable(nested)]— flatten nested list - ✅
defaults | overrides— merge dicts (Python 3.9+) - ✅
[...new Set(arr)]— remove JS array duplicates - ✅
structuredClone(obj)— deep clone without libraries - ✅
obj?.a?.b?.c ?? 'default'— safe nested access - ✅
kill -9 $(lsof -ti:3000)— kill process on port - ✅
python3 -m http.server 8000— instant local server
For more advanced JavaScript techniques, see the V8 JIT optimization guide — understanding how JavaScript actually executes makes your one-liners not just concise but also fast. If you’re working on the backend, the Node.js event loop guide covers the shell and runtime tricks that matter most for server-side debugging.
Disclosure: This post contains affiliate links. If you purchase through these links, CheatCoders earns a small commission at no extra cost to you. We only recommend tools and books we genuinely find valuable.
Free Weekly Newsletter
🚀 Don’t Miss the Next Cheat Code
You just read something most developers never learn. Get more secrets like this delivered every week — JavaScript internals, Python optimizations, AWS architectures, system design, and AI workflows.
Related: Big O Notation Explained: The Complete Guide Every Developer Must Know · Linux Commands Every Developer Must Know: The 50 Commands You Use Daily · AWS Lambda Layers: The Dependency Management Pattern You Should Be Using
Watch: 100 Days of AI on YouTube
Short videos from CheatCoders, one AI engineering topic per day.
Most viewed
- Python Decorators Explained: From Simple Wrappers to Production Patterns
- Claude Code vs Cursor vs GitHub Copilot: Choose by Workflow, and Set Up One Repo That Works With All Three
- AI Agent Frameworks in 2025: LangGraph vs CrewAI vs AutoGen vs Raw API
- Python String Methods: Every str Method With Real Production Examples
- REST API Design Best Practices: The Patterns That Make APIs a Joy to Use
Newly added
- AWS Systems Manager Parameter Store: Hierarchical Runtime Config for Coding Agents
- Amazon Cognito Identity Pools: Federate Coding-Agent Tool Callers Without Long-Lived Keys
- Amazon Athena for Coding Agents: Query Tool Audit Logs and Eval Traces on S3 Without a Warehouse
- AWS Batch for Coding Agents: Parallel Overnight PR Reviews and Long-Running Jobs Without Lambda Timeouts
- Amazon Bedrock Prompt Management: Version and A/B Test Coding-Agent System Prompts
Deep-dive PDF
Get the expanded guide for this post — extra diagrams-style checklists, failure modes, and a production walkthrough. Free when you subscribe to CheatCoders.
Already subscribed? or open the subscribe page.
Discover more from CheatCoders
Subscribe to get the latest posts sent to your email.
