π On this page
Overview
This Python cheatsheet collects the syntax, built-ins and commands you reach for most often, in one scannable page. It targets Python 3 and assumes you already write a little code β the goal is fast recall, not a tutorial.
Bookmark it, or grab the PDF, and keep it next to your editor.
Quick Reference
| Task | Snippet |
|---|---|
| F-string | f"{name} is {age}" |
| List comprehension | [x*x for x in nums if x > 0] |
| Dict comprehension | {k: v for k, v in pairs} |
| Ternary | a if cond else b |
| Enumerate | for i, v in enumerate(seq): |
| Zip | for a, b in zip(xs, ys): |
| Open file | with open(path) as f: |
| Default dict get | d.get(key, fallback) |
Syntax Examples
Functions, including default and keyword-only arguments:
def greet(name, *, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Ada") # 'Hello, Ada!'
greet("Ada", greeting="Hi") # 'Hi, Ada!'
Slicing works on any sequence β seq[start:stop:step]:
nums = [0, 1, 2, 3, 4, 5]
nums[1:4] # [1, 2, 3]
nums[::2] # [0, 2, 4]
nums[::-1] # [5, 4, 3, 2, 1, 0] (reverse)
Unpacking and the walrus operator:
first, *rest = [1, 2, 3, 4] # first=1, rest=[2, 3, 4]
if (n := len(rest)) > 2:
print(f"{n} items left")
Common Commands
Day-to-day CLI for environments and packages:
python -m venv .venv # create a virtual environment
source .venv/bin/activate # activate (macOS/Linux)
.venv\Scripts\activate # activate (Windows)
pip install requests # install a package
pip freeze > requirements.txt # snapshot deps
pip install -r requirements.txt # restore deps
python -m pytest # run tests
python -m http.server 8000 # quick static server
Best Practices
- Prefer f-strings over
%and.format()for readability. - Use
withfor files, locks and connections so they always close. - Type-hint public functions; run
mypyorpyrightin CI. - Keep one virtual environment per project; never
pip installglobally. - Reach for the standard library first β
collections,itertools,pathlib,dataclasses. - Format with
blackand lint withruffso style is never a debate.
Frequently asked questions
Is this Python cheatsheet for Python 2 or Python 3?
Python 3. Python 2 reached end of life in 2020, so every snippet here targets modern Python 3 syntax.
What is the difference between a list and a tuple in Python?
A list is mutable (you can change it after creation) and uses square brackets; a tuple is immutable and uses parentheses. Use a tuple for fixed collections and as dictionary keys.
How do I create a virtual environment in Python?
Run 'python -m venv .venv', then activate it with 'source .venv/bin/activate' on macOS/Linux or '.venv\\Scripts\\activate' on Windows.
What is an f-string in Python?
An f-string is a string literal prefixed with 'f' that lets you embed expressions inside braces, like f"{name}". It is the fastest and most readable way to format strings in Python 3.6+.