Pythonic Patterns in Python

From the Python cheat sheet ยท Best Practices ยท verified Jul 2026

Pythonic Patterns

Write idiomatic Python code.

python
# Swap variables
a, b = b, a

# Ternary
x = "yes" if condition else "no"

# Check empty
if not items:   # not len(items) == 0

# EAFP over LBYL
try:
    value = d[key]
except KeyError:
    value = default
๐Ÿ’ก EAFP (try/except) is more Pythonic than LBYL (check before acting)
โšก Use _ as a throwaway variable for values you don't need
๐Ÿ“Œ "Explicit is better than implicit" โ€” readability counts (PEP 20)
๐ŸŸข Run "import this" in the REPL to read The Zen of Python
best-practicespythonicpatterns
Back to the full Python cheat sheet