A single line can replace ten — and that's not clickbait. These Python tricks aren't flashy; they save time, cut bugs, and make your code easier to read. I'll show you concise, practical habits and small snippets you can apply today.
Stop writing boilerplate. Unpack tuples directly:
# instead of indexing
x, y = point
Use f-strings for clear formatting:
name = 'Alex'
print(f'Hello, {name}!')
Comprehensions turn loops into readable one-liners and often run faster than manual loops:
squares = [x*x for x in range(10) if x % 2 == 0]
Prefer generator expressions when you only need iteration and want lower memory use:
total = sum(x for x in large_iterable)
Use enumerate() to avoid index bugs:
for i, val in enumerate(items):
print(i, val)
Zip pairs values cleanly:
for a, b in zip(list_a, list_b):
process(a, b)
defaultdict and Counter cut down conditional code for grouped counts:
from collections import defaultdict, Counter
freq = Counter(words)
by_key = defaultdict(list)
for k, v in pairs:
by_key[k].append(v)
Use pathlib for file paths — it's cross-platform and cleaner than os.path:
from pathlib import Path
p = Path('data') / 'file.txt'
text = p.read_text()
Cache expensive calls with functools.lru_cache to skip repeated work:
from functools import lru_cache
@lru_cache()
def fib(n):
return n if n < 2 else fib(n-1) + fib(n-2)
The walrus operator (:=) helps when you want to both test and keep a value:
if (line := f.readline().strip()):
process(line)
Prefer context managers to keep resources tidy:
with open('data.csv') as f:
for line in f:
handle(line)
Type hints improve readability and help tools catch mistakes early. They don’t slow you down and often pay off in team projects:
def greet(name: str) -> str:
return f'Hi {name}'
Finally, lean on tests and small scripts. Writing one focused unit test for a tricky function saves far more time than repeatedly debugging later.
Try one trick this week. Replace a loop with a comprehension, or add a tiny test. Small changes stack quickly and make your Python code cleaner, faster, and easier to maintain.