Small, focused habits in Python save hours. This page collects real, usable tricks — not theory — so you can write clearer code, avoid bugs, and speed up development today.
Use list comprehensions and generator expressions instead of verbose loops. They read better and, for large data, generators cut memory usage: (x*x for x in nums)
keeps memory low.
Prefer enumerate()
and zip()
over manual index tracking. for i, v in enumerate(items, 1):
makes intent obvious and prevents off-by-one errors.
Format strings with f-strings. They're faster and clearer than .format()
or concatenation: f"{name} has {n} items"
.
Learn the walrus operator (:=
) for compact code that avoids repeating calls. Example: if (line := file.readline()):
reads once and checks truthiness.
Use context managers for resources: with open(path) as f:
always closes files. Build custom context managers with contextlib
to reduce boilerplate.
Cache expensive calls with functools.lru_cache
. Small decorator, big speed gains for repeated function calls with identical inputs.
Prefer pathlib.Path
over string paths. It’s clearer and cross-platform: Path('data') / 'file.csv'
.
Avoid mutable defaults in functions. Use None
and set defaults inside the function to dodge subtle bugs: def f(x=None): x = x or []
.
Use collections.defaultdict
and Counter
for common patterns. They make code shorter and eliminate many manual checks.
Use dataclasses
for simple data containers. They add docs, default repr, and less boilerplate than manual classes.
When optimizing, profile first. Use timeit
or cProfile
to find real bottlenecks before guessing.
Use type hints and a linter (mypy, flake8). Hints don’t slow you down; they catch errors early and make refactors safer.
Pick two tricks and use them for a week. Replace a manual loop with a comprehension, or add lru_cache
to a slow utility. Small, steady changes stick.
Rely on tests. Add a quick unit test when you refactor using a new trick. Tests let you move faster without fear.
Use tools: virtual environments (venv or pipx), formatters (black), and type checkers. They keep your projects tidy and reduce friction.
Read code from real projects. Copying patterns from solid libraries teaches practical uses faster than tutorials. If a trick causes confusion in your team, skip it until everyone agrees.
Want deeper examples? Check the "Python Tricks Mastery Guide" on this site for hands-on snippets and explanations. Bookmark this tag and return when you need a quick practical tip.